unitand 'a -> 'ain OCaml? For instance: # let f g a = ...">

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?

+4
source share
4 answers

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.

+6
source

if else, if unit. , a unit, g unit -> unit.

, - else, , if , , g.

+3

unit - , , ( , , )

'a . .

+1

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

+1
source

Source: https://habr.com/ru/post/1689415/


All Articles