2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You can also use ~- which is the prefix integer negation operator, avoiding the need to wrap extra parens.
Nice, I didn't know that.
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.