Reputation: 4978
I am attempting a code sample in Lesson 5, Step 6 of the Try Ocaml tutorial
We were supposed to fix this code sample:
let one =
let accum = ref -54 in
for i = 1 to ten do accum := !accum + i done ;
!accum
and here is my attempt:
let one =
let accum = ref -54 in (
for i = 1 to 10 do
accum := accum + i
done
;
!accum
)
but unfortunately I am receiving the error message:
line 2, characters 14-17: Error: This expression has type 'a -> 'a ref but an expression was expected of type int
Upvotes: 2
Views: 153
Reputation: 1172
One weirdness of the lexer of ocaml is that -54
corresponds to two tokens.
Hence, your code corresponds to
let accum = ref (-) 54 in
which yields the mentioned type error. The solution is to add parenthesis and write (-54)
.
Upvotes: 0
Reputation: 2959
You're missing parentheses around -54
.
let one =
let accum = ref (-54) in
for i=1 to 10 do
accum := !accum + i
done;
!accum
;;
ref
is a function that has type 'a -> 'a ref
, and the minus operator (-)
has type int -> int -> int
. Here, 54
is an int
but ref
is not, hence the type error message.
Upvotes: 2