Search code examples
ocamlmlcode-readability

Are there other ways to deconstruct option types in OCaml?


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?


Solution

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