pauliwago
pauliwago

Reputation: 6685

Ocaml: why these types?

Hi could someone please explain why the types are as outlined below? I understand that they would have to be int because x+y+z but the number of arguments (ie ->) seems arbitrary to me.

let f x y z = x+y+z in f 1 2 3      // int
let f x y z = x+y+z in f 1 2        // int -> int
let f x y z = x+y+z in f            // int -> int -> int -> int

Upvotes: 0

Views: 89

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

To expand slightly on valtron's answer. It is all straightforward once you understand the type of f. As valtron says, its type is int -> int -> int -> int. Fundamentally, this is the type of a function that takes an int and returns a function of type int -> int -> int. So if you were to pass just 1 to f (which you don't do in your example), you'd get back something of type int -> int -> int.

In a similar way, if you pass an int to this returned function, you get back a function of type int -> int. This is something you do in your example: f 1 2 does exactly this: it passes 1 to f, then passes 2 to the function that f returns. This second function call returns something of type int -> int, as the toplevel shows you.

In the same way, specifying three values after f returns a value of type int. This is what's happening in your first example.

Upvotes: 2

ebsddd
ebsddd

Reputation: 1026

The type of f, as you defined it, is int -> int -> int -> int. Each argument you provide f shaves an int off the type of the expression because of currying. For example, f 1 2 is int -> int, a function that takes an int and returns an int, because x and y are curried with 1 and 2, so they're not parameters anymore.

Upvotes: 1

Related Questions