3 ms·
There are two things to remember. The first is the match binding thing that tomp mentions in his reply. The second one is that in OCaml, semicolon is a separat
by arjunnarayan 12y ago
There are two things to remember. The first is the match binding thing that tomp mentions in his reply.
The second one is that in OCaml, semicolon is a separator, and not a terminator. In contrast, in C/C++, semicolon is a terminator. If you have an expression, you end it with a ";" just because.
This is not the case for OCaml. In OCaml, semicolon is used to separate two sequential expressions where only one expression is expected. Thus,
<expr1>;<expr2>
is evaluated in sequence, and can be used in a place where only one is expected. For example, if statements have the following syntax:
if <expr1> then <expr2> else <expr3>
Now if you wanted to do two things (instead of one) in the "then" block, you would simply write
if <expr1> then <expr2.1>;<expr2.2> else <expr3>
Notice that under these rules
if <expr1> then <expr2>; else <expr3>
makes no sense. Separators are not terminators. We are used to thinking of ";" as terminators because of C/C++.
- mercurial 12y agoI'll add that you need ';'-as-separator (you also use ';' in other places, such as when separating items in a list) only when calling functions which return 'unit', which is typically functions which perform side-effects (eg, close a file). That's usually a small portion of your program.
- p4bl0 12y agoif <expr1> then <expr2.1>;<expr2.2> else <expr3> Actually, this will not work, I was also confused by it. # if true then (); 1 else 2;; Error: Parse error: [str_item] or ";;" expected (in [top_phrase]) # if true then begin (); 1 end else 2;; - : int = 1 # if true then ((); 1) else 2;; - : int = 1 The confusion comes from the fact that it doesn't behave the same way in match expressions: # match true with | true -> (); 1 | false -> 2;; - : int = 1