Use of the and keyword in F# in discriminated unions

前端 未结 2 835
说谎
说谎 2021-02-13 02:38

I was faced today with the following DUs declarations:

type Grammar = Definition list

and  Definition = Def of string * Expression

and  Range =
     | Char  of         


        
2条回答
  •  野性不改
    2021-02-13 03:10

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

提交回复
热议问题