An expression was expected of type unit because it is in the left-hand side of a sequence

For this code

let example2 =
  [ fun x a -> if x then (Some a) else None
  ; fun x a -> if x then (Some a) else None
  ]
in
let example1 =
  [ fun x a -> if x then a else a
  ; fun x a -> if x then a else a
  ]
in

I’m getting the syntax error below for example2 and I can’t figure out the cause of it.

The error appears to be caused by using Some and None in example2 because example1 works fine.

What’s going on here?

Full copy-pastable error:

This expression has type 'a option but an expression was expected of type
  unit
because it is in the left-hand side of a sequence

Semi-colon in OCaml is both

  • the separator of list elements [ e1; e2; e3 ] and
  • the separator of a sequence of (typically) side-effecting expressions e1; e2; e3

While it appears as if the following is a list of option-returning functions:

[ fun x a -> if x then (Some a) else None
; fun x a -> if x then (Some a) else None
]

OCaml actually parses it as a single element list with a function that has an expression sequence in its body (using parens and indentation for illustration):

[ fun x a -> (if x then (Some a) else None;
              fun x a -> if x then (Some a) else None)
]

You can get what you want by putting parens around the functions in your list:

[ (fun x a -> if x then (Some a) else None)
; (fun x a -> if x then (Some a) else None)
]

Finally: I don’t believe the second example does what you expect either.
If you look at the type inferred for it, it is actually a list of 4-argument functions:

val example1 : (bool -> 'a -> bool -> 'b -> 'b) list = [<fun>]

Happy hacking!

5 Likes