Sanctuary: S.apFirst and S.apSecond

Created on 1 Nov 2016  路  12Comments  路  Source: sanctuary-js/sanctuary

Does it make sense to provide the following two functions?

S.maybeFirst returns the first Maybe value only if both arguments are Just, otherwise return Nothing.

S.maybeFirst :: Maybe a -> Maybe b -> Maybe a
> S.maybeFirst(S.Nothing(), S.Nothing())
Nothing()

> S.maybeFirst(S.Just(1), S.Nothing())
Nothing()

> S.maybeFirst(S.Just(1), S.Just('2'))
Just(1)

S.maybeSecond returns the second Maybe value only if both arguments are Just, otherwise return Nothing.

S.maybeSecond :: Maybe a -> Maybe b -> Maybe b
> S.maybeSecond(S.Nothing(), S.Nothing())
Nothing()

> S.maybeSecond(S.Just(1), S.Nothing())
Nothing()

> S.maybeSecond(S.Just(1), S.Just('2'))
Just('2')

Or the above functions can be made by composing existing sanctuary functions? Please advice :)

good first contribution

Most helpful comment

something like this shuold do the trick

const maybeFirst = first = lift2(a => _ => a)
const maybeSecond = second = lift2(_ => a => a)

All 12 comments

something like this shuold do the trick

const maybeFirst = first = lift2(a => _ => a)
const maybeSecond = second = lift2(_ => a => a)

Thanks for the trick @safareli

Very nice, @safareli. We can even replace a => _ => a with K, and _ => a => a with K(I):

//    maybeFirst :: Maybe a -> Maybe b -> Maybe a
const maybeFirst = S.lift2(S.K);

//    maybeSecond :: Maybe a -> Maybe b -> Maybe b
const maybeSecond = S.lift2(S.K(S.I));

also they would work on any applicative Either, Future ...

As @safareli points out, maybeFirst and maybeSecond are (<*) and (*>) respectively. I don't know if that already exists in the sanctuary ecosystem, but it'd be great to have.

As safareli points out, maybeFirst and maybeSecond are (<*) and (*>) respectively. I don't know if that already exists in the sanctuary ecosystem, but it'd be great to have.

Only if we can call them S.icecreamL and S.icecreamR. In all seriousness though, these would be useful additions.

:icecream:

Do (<*) and (*>) go by other names? Valid JavaScript identifiers would be nice. ;)

They go by the name of applyFirst and applySecond in PS, so perhaps apFirst/apSecond or apL/apR?

Thanks, Scott. apFirst and apSecond sound very good to me. :)

apFirst apSecond sounds good, we could also add same for '>>' and '<<' as chain.... Maybe they could be decleared in s-type-classes?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davidchambers picture davidchambers  路  8Comments

zfoxdev picture zfoxdev  路  8Comments

fnune picture fnune  路  3Comments

davidchambers picture davidchambers  路  8Comments

arsaniwilliam picture arsaniwilliam  路  9Comments