base icon indicating copy to clipboard operation
base copied to clipboard

Request: Base.Option.value_merge

Open mroch opened this issue 3 years ago • 2 comments

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.

mroch avatar Sep 16 '21 18:09 mroch

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

bcc32 avatar Sep 16 '21 20:09 bcc32

@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).

benjub avatar Sep 22 '21 12:09 benjub

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.

tdelvecchio-jsc avatar Jun 06 '23 14:06 tdelvecchio-jsc