Difference between unit type and 'a in ocaml

Viewed 3871

What's the difference between unit -> unit and 'a -> 'a in OCaml?

For example:

# let f g a = if (g a > a) then a ;;
val f : (unit -> unit) -> unit -> unit = <fun>

# let f g a = if (g a > a ) then a else a;;
val f : ('a -> 'a) -> 'a -> 'a = <fun>

Why does the first one give unit -> unit and the second 'a -> 'a?

3 Answers

Note that in OCaml, if is an expression: it returns a value.

The key to understand your problem is that

if condition then a

is equivalent to

if condition then a else ()

The typing rules for if are the following:

  • the condition should have type bool
  • both branches should have the same type
  • the whole if expression has the same type as the branches

In other words, in if cond then a, a should have type unit.

The if expression in the first variant has no else clause, so the true branch of the if expression must have type unit. This means that the type of a must be unit as well, and g must have type unit -> unit.

In the second variant, due to the else clause, the only requirement is that the true and false branches of the if expression have the same type, so the type generalizes, and so does the type of g.

Related