OCaml's option type is really useful in cases where you have functions that might not return anything. But when I use this in many places, I find it cumbersome to handle the Some
case and the None
case all the time in a match ... with
.
For example,
let env2 = List.map (fun ((it,ie),v,t) ->
match t with
| Some t -> (v,t)
| None ->
begin
match it with
| Some it -> (v,it)
| None -> failwith "Cannot infer local vars"
end) ls_res in
Are there any other ways to deconstruct the option type in a concise manner?
For simple cases, you can match several things at once:
match t, it with
| Some t, _ -> (v, t)
| None, Some it -> (v, it)
| None, None -> failwith "Cannot infer local vars"
This is something I do all the time. I'm told the compiler is good with this construct (it doesn't actually generate an extra pair).
Depending on what you want to do, there are a variety of things you could write to help deal with these. For this pattern, I'd suggest writing something like the following:
let or_else opt1 opt2 = match opt1 with
| Some _ -> opt1
| None -> opt2
And then restructuring your code as:
let env2 = List.map (fun ((it,ie),v,t) ->
match (or_else opt1 opt2) with
| Some t -> (v,t)
| None -> failwith "Cannot infer local vars") ls_res in
If you've got more than this number of options, then you can fold or_else
over them in a list:
let a = [None; None; Some 1; Some 2;];;
List.fold a ~init:None ~f:or_else;;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With