简体   繁体   中英

Why this OCaml syntax error

I have this code in Ocaml

let double x = 2 * x

let triple x = 3 * x

let s = "Hello" in print_endline s

let () = triple 10 |> string_of_int |> print_endline

and when compiling with ocamlc file.ml this gives the error:

File "file.ml", line 5, characters 16-18:
Error: Syntax error

If I put ;; at the end of line 3 like this

let triple x = 3 * x;;

of if I comment characters 16-18 in line 5 like this

let s = "Hello" (* in print_endline s *)

the syntax error goes away.

Can someone explain the reason of the syntax error, and what each of these two corrections do to resolve it?

let s = "Hello" in print_endline s is not a top level declaration even if it starts with let , it's a let .. in expression. If you don't terminate the preceding expression with ;; it expects what comes next to be part of that expression instead of interpreting it as a top level declaration.

If you remove the in ... part you're changing it from a let ... in expression to a top level let declaration.

You can also turn it into a top level declaration like this:

let () = let s = "Hello" in print_endline s

Edit:

One way of thinking about this is, if instead of having

let triple x = 3 * x

let s = "Hello" in print_endline s

you replace let s = ... in ... with a simpler expression like just "Hello" :

let triple x = 3 * x

"Hello"

This is equivalent to

let triple x = 3 * x "Hello"

which will be parsed as applying the argument "Hello" to the function x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM