I have a let.ml
containing below 2 lines:
let x = 1 in x + 1
let y = 1 in y + 1
When compile them with ocamlc
, it says below error:
File "let.ml", line 2, characters 10-12:
2 | let y = 1 in y + 1
^^
Error: Syntax error
But if I only keep any single line the compile is OK.
Why the error?
You have an error because your program has two bare expressions (let ... in ...
is an expression) at its top-level. There is no way for the compiler to know where one expression ends and the next begins. The naive way to fix this is to use ;;
to tell it where the first one ends.
let x = 1 in x + 1;;
let y = 1 in y + 1
This prevents this from being parsed as below. Remember that whitespace means something to you, but much less to OCaml.
let x = 1 in (x + 1 let y = 1 in y + 1)
The better way to deal with this is for a well-formed OCaml program to only contain top-level definitions.
E.g.
let x = 2
let y = 2
Even if we get rid of the newline, this still parses fine.
let x = 2 let y = 2
Of course, your program does nothing, so this is all very academic.