Reputation: 1
Let me explain what I'm trying to do first. I'm learning about Ocaml types, and I define a new type, say int2
that is the same as int
.
# type int2 = int;;
type int2 = int
So far so good.
Now I want to define a function called add_five
that take an argument of type int
and returns a value of type int2
# let add_five (x : int) = (x + 5 : int2);;
val add_five : int -> int2 = <fun>
Great! Now I want to apply this to one positive number, and one negative number to confirm that it works correctly.
# add_five 5;;
- : int2 = 10
That worked correctly!
# add_five -7;;
Error: This expression has type int -> int2
but an expression was expected of type int
What? I don't understand why this is happening. I explicitly told Ocaml I wanted a return function of type int2
, so why is it claiming it needed to be type int
?
Upvotes: 0
Views: 256
Reputation: 35210
add_five -7
is parsed as (add_five) - (7)
, i.e., the -
operator is infix. So add_five
is expected to be something from which you can subtract 7
, i.e., a value of type int
. The solution is either to parenthesize it (-7)
or use the infix form of the negation ~-7
Upvotes: 4