janestreet/base

Request: Base.Option.value_merge

Closed this issue · 3 comments

mroch commented

As with Option.map vs Option.value_map, it'd be useful (albeit rarely!) to have a value_merge function:

let value_merge a b ~default ~f =
  match a, b with
  | None, None -> default
  | None, x | x, None -> x
  | Some a, Some b -> Some (f a b)

I know, I know, I can do Option.merge a b ~f |> Option.value ~default but wanted to throw it out there.

bcc32 commented

Thanks for the suggestion, @mroch. Do you have a use case in mind for where this function might come up commonly?

@mroch: regardless of its usefulness, I think your proposed function should be:

let value_merge a b ~default ~f =
  match a, b with
  | None, None -> default
  | None, Some x | Some x, None -> x
  | Some a, Some b -> f a b

(which indeed corresponds to fun a b ~default ~f -> Option.merge a b ~f |> Option.value ~default).

I have not heard of much need for a function like this, and as it's easy enough to just write Option.merge a b ~f |> Option.value ~default, we would rather not clutter Base with an extra function. I'm closing this issue for now, feel free to re-open it if you have a strong argument for adding it.