Passing down optional arguments

imagine I have two nested functions that both take the same optional argument:

let fn1 ?opt _ = _

let fn2 ?opt _ = match opt with Some opt -> fn1 ~opt () | None -> fn1 ()

is there a way of writing this more nicely? I was hopping something like that would have just worked but no luck:

let fn1 ?opt _ = _

let fn2 ?opt _ = fn1 ~opt
let fn2 ?opt = fn1 ?opt
2 Likes

Oh that’s awesome! I have more questions now :smiley: does this ? operator have a name when used as an expression? Is there more usecases for that?

It’s not an operator, it’s syntax. It is used like ~, but for optional parameters only and assumes that the corresponding variable already has an option type.
Example:

let f1 ?(opt = 42) () = ignore (opt + 1)
let _ =
  f1 ~opt:0 (); (* Pass an actual value *)
  f1 ?opt:(Some 1) (); (* Pass an actual value through an option *)
  f1 ?opt:(None) (); (* Explicitly set no value; default will be used if any *)
  let opt = Some 3 in
  f1 ?opt () (* Punning *)
5 Likes