模块名称后的点语法
Dot syntax after module name
有大量类似于以下示例的语法示例
Json.Encode.(object_([("type", string(m.type_)), ("label", string(m.label))]))
这与调用 Json.Encode.object_(([("type", string(m.type_)), ("label", string(m.label))]))
有何不同?我何时会使用一种语法或另一种语法?
语法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))
])
在像 Json.Encoding 引入的那样处理 DSL 时,这种本地开放语法非常有用,同时仍然可以清楚地知道本地开放引入的项目的使用位置。相反,通过显式限定模块(Json.Encode.string
),语法可能更重,但每个实体的来源更清晰。
另一种经常使用的折衷方法是为常用模块提供短别名:
module Enc = Json.Encode;
Enc.object_([
("type", Enc.string(m.type_)),
("label", Enc.string(m.label))
])
有大量类似于以下示例的语法示例
Json.Encode.(object_([("type", string(m.type_)), ("label", string(m.label))]))
这与调用 Json.Encode.object_(([("type", string(m.type_)), ("label", string(m.label))]))
有何不同?我何时会使用一种语法或另一种语法?
语法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))
])
在像 Json.Encoding 引入的那样处理 DSL 时,这种本地开放语法非常有用,同时仍然可以清楚地知道本地开放引入的项目的使用位置。相反,通过显式限定模块(Json.Encode.string
),语法可能更重,但每个实体的来源更清晰。
另一种经常使用的折衷方法是为常用模块提供短别名:
module Enc = Json.Encode;
Enc.object_([
("type", Enc.string(m.type_)),
("label", Enc.string(m.label))
])