Difference between block type and "a in ocaml
What is the difference between unit -> unitand 'a -> 'ain OCaml?
For instance:
# 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 give the unit -> unitsecond 'a -> 'a?
Note that in OCaml there ifis an expression: it returns a value.
The key to understanding your problem is that
if condition then a
equivalently
if condition then a else ()
Entry rules for the iffollowing:
- the condition must be of type
bool - both branches must be of the same type
- the whole if expression is of the same type as the branches
In other words, in if cond then a, amust be of type unit.
There is no else clause in the if statement in the first version, so the true branch of the if statement must be of type one. This means that type a must also be one, and g must have a block of type →.
In the second option, due to the else clause, the only requirement is that the true and false branches of the if expression are of the same type, so the type is generalized, as well as the type g. answered Florian Weimer