2

Why is there a semicolon at the end of Proc.num_stack_slots.(i) <- 0 in the following code? I thought semicolons are separators in OCaml. Can we always put an optional semicolon for the last expression of a block?

for i = 0 to Proc.num_register_classes - 1 do
  Proc.num_stack_slots.(i) <- 0;
done;

See https://github.com/def-lkb/ocaml-tyr/blob/master/asmcomp/coloring.ml line 273 for the complete example.

glennsl
  • 28,186
  • 12
  • 57
  • 75
Wickoo
  • 6,745
  • 5
  • 32
  • 45

1 Answers1

13

There is no need for a semicolon after this expression, but as a syntactic courtesy, it is allowed here. In the example, you referenced, there is a semicolon, because after it a second expression follows.

Essentially, you can view a semicolon as a binary operator, that takes two-unit expressions, executes them from left to right, and returns a unit.

val (;): unit -> unit -> unit

then the following example will be more understandable:

for i = 1 to 5 do
    printf "Hello, ";
    printf "world\n"
done

here ; works just a glue. It is allowed to put a ; after the second expression, but only as the syntactic sugar, nothing more than a courtesy from compiler developers.

If you open a parser definition of the OCaml compiler you will see, that an expression inside a seq_expr can be ended by a semicolumn:

seq_expr:
  | expr        %prec below_SEMI  { $1 }
  | expr SEMI                     { reloc_exp $1 }
  | expr SEMI seq_expr            { mkexp(Pexp_sequence($1, $3)) }

That means that you can even write such strange code:

let x = 2 in x; let y = 3 in y; 25
ivg
  • 34,431
  • 2
  • 35
  • 63
  • Your last example does not compile without warning though (Warning 10: this expression should have type unit). Each expression in a sequence (except for the last) is expected to be of type unit. – Po' Lazarus Oct 09 '14 at 20:38
  • 1
    it compiles, it is only warning, that says, that you're doing something wrong. And compiler is true about this. Because semantically it is a nonsense. I'm just demonstrating to you syntax capabilities. With semicolumn, syntactically, you can separate any expressions, but if they do not have a unit type, then you will get a warning. – ivg Oct 09 '14 at 20:55
  • Yes I know. I just thought it was worth mentioning in your answer. – Po' Lazarus Oct 09 '14 at 21:20