Use of the and keyword in F# in discriminated unions

大城市里の小女人 提交于 2019-12-04 16:21:05

问题


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?


回答1:


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




回答2:


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).



来源:https://stackoverflow.com/questions/7154418/use-of-the-and-keyword-in-f-in-discriminated-unions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!