Are there any elvis like operator in Ocaml ?
Any sort of optional chaining that return the right value when the left one is empty, a default value operator, like the |>
operator with opposite effect.
If not what are the good practices ?
As an example of a use case :
let get_val val_1 val_2 =
if (val_1) then (val_1) else (val_2);;
Are there any syntactic sugar ?
First, in OCaml if ... then ... else ...
is an expression and thus there is no needs to have a distinct ternary operator.
Second, OCaml has optional arguments.
If I guess correctly the supposed semantics of your get_val
function, it can be written:
let default = []
let get_val ?(val_1=default) () = val_1
which gives you []
as the default value when the named argument val_1
is absent
let () =
assert ([] = get_val ())
or the val_1
argument otherwise:
let () =
assert ([2;3;4] = get_val ~val_1:[2;3;4] ())