Reputation: 97
The expression is f x y = 1 + (x 1) + (y 1)
which has a type of (int->int)->(int->int)->int
. I don't understand how it has that type. why isn't it int->int
?
Upvotes: 1
Views: 100
Reputation: 25812
let f x y = 1 + (x 1) + (y 1)
you have (x 1)
, so x must be a function
you have 1 + (x 1)
, so (x 1)
must return an int, also 1 is int, so x: int -> int <fun>
using the same induction as above, y: int -> int <fun>
you have f x y
, so f is a function, we already know what type x and y is and also know the right handside of =
must be an int, so f: (int -> int) -> (int -> int) -> int
Upvotes: 2
Reputation: 35210
When OCaml infers the type of expression
let f x y = 1 + (x 1) + (y 1)
It will think something like this:
Since (+)
has type int -> int
, expression (x 1)
should have type int
, as it occurs on the right hand side of +
.
Since x 1
should evaluate to int
and it is an application, it should have type _ -> int
. As 1
is an int
literal, it has type int -> int
.
Using the same logic we can infer, that y
also has type int -> int
.
Upvotes: 3
Reputation: 194
Since you have function applications (x 1) and (y 1). x and y are treated like functions that take an int argument and return an int.
So x is type (int -> int) and y is type (int -> int). 1 is applied on both x and y. So if 1 is applied on something that is type (int -> int) you get something that is type int. So your whole function returns 1 + int + int which is basically int.
Upvotes: 3
Reputation: 66793
The expression (x 1)
requires x to be a function of type int -> 'a
. Similarly for (y 1)
. The rest follows from this.
Upvotes: 2