模块名称后的点语法

时间:2018-07-17 19:10:12

标签: syntax reason

大量的语法示例与下面的示例类似

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

与调用Json.Encode.object_(([("type", string(m.type_)), ("label", string(m.label))]))有什么不同?何时使用一种或另一种语法?

1 个答案:

答案 0 :(得分:8)

语法M.( expr )在表达式expr内本地打开模块M。换句话说,它将表达式中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所提供的DSL)时非常有用,同时仍可以清楚地知道本地开放所使用的项在哪里使用。相反,使用模块(Json.Encode.string的显式限定,语法可能更重,但是每个实体的来源都更清楚。

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

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