我不熟悉OCaml,但参与了一些OCaml代码的分析。这段代码令我费解。基于运算符优先级的正确分组是什么?
let new_fmt () =
let b = new_buf () in
let fmt = Format.formatter_of_buffer b in
(fmt,
fun () ->
Format.pp_print_flush fmt ();
let s = Buffer.contents b in
Buffer.reset b;
s
)这里有三个操作符:";“、”“和”有趣“。根据参考手册,优先顺序是逗号>分号>乐趣,我认为这将导致下面的分组。哪个是由OCaml编译器选择的?还是有另一个分组是正确的?
第1组:
let new_fmt () =
let b = new_buf () in
let fmt = Format.formatter_of_buffer b in
((fmt,
fun () ->
Format.pp_print_flush fmt ());
(let s = Buffer.contents b in
Buffer.reset b;
s)
)第2组:
let new_fmt () =
let b = new_buf () in
let fmt = Format.formatter_of_buffer b in
(fmt,
(fun () ->
Format.pp_print_flush fmt ();
let s = Buffer.contents b in
(Buffer.reset b;
s))
)发布于 2014-10-07 02:48:07
分组2是正确的。
如果您不确定如何解析这些内容,编辑器助手可能会帮助您(有时):ocaml模式或tuareg模式(可能还有其他编辑器帮助程序)应该为您提供与代码解析方式相对应的自动缩进:
let new_fmt () =
let b = new_buf () in
let fmt = Format.formatter_of_buffer b in
( fmt,
fun () ->
Format.pp_print_flush fmt ();
let s = Buffer.contents b in
Buffer.reset b;
s
)let s = ...的标识值低于fun () ->,这意味着该部分位于fun () -> ...中。如果它在fun () ->之外,则应该在相同的fun () ->级别上以不同的方式缩进。
另一个非常精确但可能过于复杂的方法是检查代码是如何被ocamlc -dparsetree source.ml直接解析的。
发布于 2014-10-07 02:32:06
至于它的价值,在代码中使用了另一个操作符。它没有符号表示:将函数应用于OCaml中的值的操作由并置表示。这个运算符的优先级高于其他操作符。
这段代码
fun () -> a ; b解析为
fun () -> (a; b)不像
(fun () -> a) ; b这是因为正如您所说的,;比fun具有更高的优先级(尽管这个术语有点可疑)。
类似的
let c = d in e; f解析为
let c = d in (e; f)不像
(let c = d in e); f因此,最后的表达式解析如下:
(fmt,
fun () -> (Format.pp_print_flush fmt ();
let s = Buffer.contents b in
(Buffer.reset b; s))
)https://stackoverflow.com/questions/26227372
复制相似问题