ocaml - Why two let expressions lead to compile error? - Stack Overflow

admin2025-04-27  3

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?

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?

Share Improve this question edited Jan 11 at 15:20 Chris 37k6 gold badges33 silver badges55 bronze badges asked Jan 11 at 14:53 smwikipediasmwikipedia 64.6k98 gold badges331 silver badges507 bronze badges 3
  • You may need ;; to separate multiple statements IIRC – Bergi Commented Jan 11 at 14:58
  • What exactly is the goal here, how do you want to use let.ml? How do you want to call it and what output do you expect? – Bergi Commented Jan 11 at 14:59
  • @Bergi I am just learning OCaml. And this time I just want to try the ocamlc with some simple code. The ;; does work. But I am not using utop, why should I need it? – smwikipedia Commented Jan 11 at 15:09
Add a comment  | 

1 Answer 1

Reset to default 1

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.

转载请注明原文地址:http://www.anycun.com/QandA/1745707727a91108.html