首页
学习
活动
专区
圈层
工具
发布

OCaml优先
EN

Stack Overflow用户
提问于 2014-10-07 01:39:37
回答 2查看 467关注 0票数 1

我不熟悉OCaml,但参与了一些OCaml代码的分析。这段代码令我费解。基于运算符优先级的正确分组是什么?

代码语言:javascript
复制
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组:

代码语言:javascript
复制
  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组:

代码语言:javascript
复制
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))
  )
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-07 02:48:07

分组2是正确的。

如果您不确定如何解析这些内容,编辑器助手可能会帮助您(有时):ocaml模式或tuareg模式(可能还有其他编辑器帮助程序)应该为您提供与代码解析方式相对应的自动缩进:

代码语言:javascript
复制
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直接解析的。

票数 2
EN

Stack Overflow用户

发布于 2014-10-07 02:32:06

至于它的价值,在代码中使用了另一个操作符。它没有符号表示:将函数应用于OCaml中的值的操作由并置表示。这个运算符的优先级高于其他操作符。

这段代码

代码语言:javascript
复制
fun () -> a ; b

解析为

代码语言:javascript
复制
fun () -> (a; b)

不像

代码语言:javascript
复制
(fun () -> a) ; b

这是因为正如您所说的,;fun具有更高的优先级(尽管这个术语有点可疑)。

类似的

代码语言:javascript
复制
let c = d in e; f

解析为

代码语言:javascript
复制
let c = d in (e; f)

不像

代码语言:javascript
复制
(let c = d in e); f

因此,最后的表达式解析如下:

代码语言:javascript
复制
(fmt,
 fun () -> (Format.pp_print_flush fmt ();
            let s = Buffer.contents b in
            (Buffer.reset b; s))
)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26227372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档