Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between unit type and 'a in ocaml

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?

like image 858
Thenad Avatar asked Nov 16 '17 20:11

Thenad


People also ask

What is unit type in OCaml?

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.

What is type A in OCaml?

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.

What does a represent in OCaml?

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.

How do you specify types in OCaml?

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.


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

like image 97
Étienne Millon Avatar answered Oct 17 '22 19:10

Étienne Millon


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.

like image 43
Titouan Freville Avatar answered Oct 17 '22 19:10

Titouan Freville