Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 609
Jason Yeo Avatar asked Dec 20 '22 09:12

Jason Yeo


2 Answers

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

like image 58
Jeffrey Scofield Avatar answered Feb 24 '23 02:02

Jeffrey Scofield


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;;
like image 40
Impredicative Avatar answered Feb 24 '23 02:02

Impredicative