本文介绍了for循环中的分号单表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在下面的代码中Proc.num_stack_slots.(i) 末尾有一个分号?我认为分号是 OCaml 中的分隔符.我们可以总是在块的最后一个表达式中添加一个可选的分号吗?

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;

参见 https://github.com/def-lkb/ocaml-tyr/blob/master/asmcomp/coloring.ml 完整示例的第 273 行.

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

推荐答案

这个表达式后不需要分号,但是为了语法上的礼貌,这里是允许的.在您引用的示例中,有一个分号,因为在第二个表达式之后.

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 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.

如果打开 OCaml 编译器的解析器定义,您将看到 seq_expr 中的表达式可以以半列结尾:

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

这篇关于for循环中的分号单表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:57