emmanueltouzery / prelude-ts

Functional programming, immutable collections and FP constructs for typescript and javascript
ISC License
377 stars 21 forks source link

Added Option.zip #78

Closed Annoiiyed closed 6 months ago

Annoiiyed commented 6 months ago

Hello again!

We at Timewax occasionally run into a function we think would probably be useful in the library, usually because we have a utility function of our own that we use a lot.

We've forked the repo and will be adding these for our own use regardless, but, obviously we do want to contribute back to your library if desired.

In this case, the Option.zip function:

Option.of(5).zip(Option.of("A")) // => Some(Tuple2(5, "A"))

Please let us know what you think!

emmanueltouzery commented 6 months ago

Thank you for the PR, I really appreciate it!

And I'm really glad you're getting so much mileage out of prelude :+1:

i wouldn't expect that function to be really standard, but I see that scala actually has Option.zip. vavr doesn't.

I'd do that:

Option.liftA2(Tuple2.of)(Option.of(2), Option.of(3))

Possibly in two lines:

const optionZip = Option.liftA2(Tuple2.of);
optionZip(Option.of(2), Option.of(3))

It's a little more verbose and a little abstract though...

My first thought is that the liftA2 approach is good enough, given that i don't expect this to be needed all that much. But I'll leave the PR open a little longer if you have more feedback or anything.

Annoiiyed commented 6 months ago

Oh! I must have misunderstood Option.liftAp2, then. Thanks!

emmanueltouzery commented 6 months ago

yeah, if you look at the type definition for option.lifta2...

liftA2<T,U,V>(fn:(v1:T,v2:U)=>V): (p1:Option<T>, p2:Option<U>) => Option<V>

i mean it looks a mouthful, but it's not that bad when you think about it. You "lift" the function (Tuple2.of in this case) to work with the functor (Option in this case).

and then you have liftA2 on Either, Future as well and so on. haskell has liftA2 as well, but there people would rather use the <$> and <*> operators.