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
?
unit — The Unit Value The built-in printing functions return type unit, for example; the value of a while or for loop (both of which are expressions, not "statements") is also of type unit. OCaml uses this convention to help catch more type errors.
The type 'a is a type variable, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are polymorphic in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.
The ' is simply part of the variable name. And yes foo :: bar , where foo is an element of type a and bar is a list of type a, means "the list that has foo as its first element, followed by the elements of bar". So the meaning of the match statement is: If xs is the empty list, the value is 0.
OCaml has two ways of specifying types, they can be done inline: let intEq (x : int) (y : int) : bool = ... I believe the latter is preferred, since it more cleanly separates the specification (type) from the implementation (code). Show activity on this post.
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:
bool
In other words, in if cond then a
, a
should have type unit
.
unit
is the type used when nothing is return by a function (basically, functions who are printing things)
'a
is a neutral type. It is a placeholder for any type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With