我不熟悉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
)
这里有三个运算符:“;”,“,”和“ fun”。根据参考手册,优先顺序为逗号>分号> fun,我认为这会导致以下分组。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))
)
分组2是正确的分组。
如果不确定如何解析,编辑器助手可能会(有时)为您提供帮助:ocaml-mode或tuareg-mode(以及其他编辑器助手)应为您提供与代码解析方式相对应的自动缩进:
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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句