Usage of ; and ;; in ocamlsteemCreated with Sketch.

in ocaml •  4 years ago  (edited)

When I started to learn programming, I used a lot ; to separate statements. Later I discorvered Python, and it was quite strange. But more strange was when I started Ocaml. You have ; but also ;; and sometimes you can read source codes whitout them.

image.png

Here a first example of code, the famous Hello World :

let () = 
   let hello = "Hello World !" in
   print_endline hello

Or this version

let () =
   print_string "Hello ";
   print_string "World ";
   print_endline "!"

Or

print_string "Hello ";;
print_string "World ";;
print_endline "!";;

Or
let () =
print_string
"Hello "
;
print_string
"World "
; print_endline
"!";;

Usage of ; operator

In Ocaml everything is an expression or a declaration. So a program is a hierarchy of expressions and declarations. There is no difference between a space or a new line.

Sometimes, when you are doing a sequence of side effectfs, to read data, print data .... you need to separate them by the ; operator.

For functions that aren't doing side effects, you doesn't need to use ;

Usage of ;; operator

You never use it in your source code. Stop, I will repeat you never use ;; in your source code. So what's that for, why so many articles in internet use them.

This token divide top level module items. His usage is optional and discouraged. But there is one very useful use case : interaction with Ocaml interpreter.

Ocaml is distributed with an interactive interpreter. This interpreter is sometimes designated as the REPL because of the cycle describing how it works :

  1. Read
  2. Eval
  3. Print
  4. Loop

As explained earlier, new line have no different meaning than a space in an OCaml source code. So the interpreter need to know when you have finished to write your code, in order to stop reading the code and start the Eval step.

How do you do that ? you write ;; and enter

So never use ;; in your source code !, there is no value in using them.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!