在可区分联合中使用 F# 中的 and 关键字
我今天面临以下 DU 声明:
type Grammar = Definition list
and Definition = Def of string * Expression
and Range =
| Char of char
| Range of char * char
为什么在这里使用关键字 and
而不是 type
?
I was faced today with the following DUs declarations:
type Grammar = Definition list
and Definition = Def of string * Expression
and Range =
| Char of char
| Range of char * char
Why would one use the keyword and
instead of type
, here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Grammar
和Definition
的定义需要and
才能正确编译。首先列出Grammar
类型,但取决于稍后定义的Definition
类型。为了正确编译,它必须与and
链接,告诉 F# 编译器类型定义是依赖/相关的。没有理由以这种方式声明
Range
,而应该使用type
来声明The
and
is needed for the definitions ofGrammar
andDefinition
to compile correctly. TheGrammar
type is listed first but depends on the typeDefinition
which is defined later. In order to compile properly it must be linked withand
which tells the F# compiler the type definitions are dependent / related.There is no reason for
Range
to be declared in such a way and should be declared withtype
它用于创建相互相关的类型。通常在 F# 中,您需要在使用每种类型之前对其进行转发声明 - 但这并不总是可行,例如,当您需要引入对两种或多种类型的循环依赖时。
在您的示例中,如果您使用
type
而不是and
定义Definition
,您将无法编译Grammar 的定义
,除非您更改了它们的定义顺序。您发布的代码示例并不完全是一个好的代码示例,因为其中不需要相互关系 - 您可以更改顺序。 (除非有更多的类型进一步定义,这取决于上面的内容)。
It's used to create mutually related types. Usually in F#, you need to forward declare each type before you use it - but this isn't always possible, for example when you need to introduce a cyclic dependency on two or more types.
In your example, if you defined
Definition
withtype
rather thanand
, you wouldn't be able to compile the definition ofGrammar
, unless you switched the order in which they're defined.The code example you've posted isn't exactly a good one, because the mutual relation isn't necessary in it - you can change the order. (Unless there were some more types defined further down which depended on the above).