在可区分联合中使用 F# 中的 and 关键字

发布于 2024-12-01 01:04:00 字数 247 浏览 1 评论 0原文

我今天面临以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゝ偶尔ゞ 2024-12-08 01:04:01

GrammarDefinition 的定义需要 and 才能正确编译。首先列出 Grammar 类型,但取决于稍后定义的 Definition 类型。为了正确编译,它必须与 and 链接,告诉 F# 编译器类型定义是依赖/相关的。

没有理由以这种方式声明 Range,而应该使用 type 来声明

The and is needed for the definitions of Grammar and Definition to compile correctly. The Grammar type is listed first but depends on the type Definition which is defined later. In order to compile properly it must be linked with and 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 with type

§普罗旺斯的薰衣草 2024-12-08 01:04:01

它用于创建相互相关的类型。通常在 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 with type rather than and, you wouldn't be able to compile the definition of Grammar, 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文