代码之家  ›  专栏  ›  技术社区  ›  Abraham P

模块名称后的点语法

  •  1
  • Abraham P  · 技术社区  · 8 年前

    有许多语法示例与下面的示例类似

    Json.Encode.(object_([("type", string(m.type_)), ("label", string(m.label))]))
    

    这和打电话有什么不同 Json.Encode.object_(([("type", string(m.type_)), ("label", string(m.label))])) 我什么时候用一种语法呢?

    1 回复  |  直到 8 年前
        1
  •  8
  •   octachron    8 年前

    语法 M.( expr ) 本地打开表达式中的模块m expr . 换句话说,它将 Module 在表达式中。 例如,在您的情况下

    Json.Encode.(object_([("type", string(m.type_)), ("label", string(m.label))]))
    

    转换为

    Json.Encode.object_([
      ("type", Json.Encode.string(m.type_)),
      ("label", Json.Encode.string(m.label))
     ])
    

    这种本地开放式语法在处理DSL时非常有用,就像JSON.Encoding引入的语法一样,虽然仍然清楚地知道本地开放式引入的项在哪里被使用。相反,具有明确的模块限定性( Json.Encode.string )的语法可能更重,但每个实体的来源更清楚。

    另一个常用的折衷方法是为常用模块提供短别名:

     module Enc = Json.Encode;
     Enc.object_([
      ("type", Enc.string(m.type_)),
      ("label", Enc.string(m.label))
     ])