JJ E
JJ E

Reputation: 11

Parametric Polymorphism question in OCaml

This polymorphic function allows us to flip the order of the arguments of an arbitrary curried function:

 # let flip f x y = f y x ;;
   val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c

That is flip takes a function of type 'a -> 'b -> 'c and returns a function of type b -> 'a -> 'c. But I actually don't get it, why it is correct? how the order of a,b,c are determined by ? Pretty confused about it, can anyone explain for me, thank you.

Upvotes: 0

Views: 165

Answers (2)

Perhaps this might help you. Instead of,

let flip f x y = f y x ;;

write the equivalent definition,

let flip f = fun x y -> f y x;;

now look at the type,

val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c

it's the same as this, with parenthesis,

val flip : ('a -> 'b -> 'c) -> ('b -> 'a -> 'c)

the function flip takes a function f of type 'a -> 'b -> 'c and returns the function \fun x y -> f y x of type 'b -> 'a -> 'c.

Upvotes: 1

nekketsuuu
nekketsuuu

Reputation: 2067

Let's consider types of all given variables. If we have f : 'a -> 'b -> 'c, then from the code f y x in the function definition we have y : 'a and x : 'b. Also a return type of flip (i.e. a type of flip f x y) is a type of f y x, so 'c.

The function flip has three parameters, f, x, and y in this order. And it returns a value of f y x. Therefore the type of flip is:

flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
       ----------------    --    --    --
         |                  |     |     |_ The type of the return value, (f y x)
         |                  |     |_ The type of y
         |                  |_ The type of x
         |_ The type of f

Upvotes: 3

Related Questions