How to apply many options or results

Let’s say one has:

let x = Some ("hello world")
let y  = Some ("!")

And a function like this:

let f = (x:string, y:string) => x ++ y

How do I apply more than an Option to some function like f?

Some attemp:

open Belt

let f = (x:string, y:string) => x ++ y

let x = Some ("hello world")
let y = Some ("!")

let z = x->Option.flatMap (x => y->Option.map(y => f (x, y)))->Option.getWithDefault ("")

Does Rescript offers some other alternative? It would be nice to have Option.lift2:

let z = Option.lift2 (f, x, y)->Option.getWithDefault ("")

lift2 and variants thereof is pretty easy to define. Here’s what I do:

let map2 = (o1, o2, ~f) =>
  switch (o1, o2) {
  | (Some(a), Some(b)) => Some(f(a, b))
  | _ => None
  }

I’m not sure something like this will ever be added to Belt. In a lot of cases it’s far better to use a switch statement and leverage pattern matching to do exactly what you want instead of composing functional concepts together that have to be coerced into doing the right thing.

In my codebase we do this type of lifting often enough that defining a function for it saves a bit of bundle size.

2 Likes