17

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?

devoured elysium
  • 90,453
  • 117
  • 313
  • 521

2 Answers2

24

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

JaredPar
  • 673,544
  • 139
  • 1,186
  • 1,421
  • 19
    Also, `Grammar` could be placed after the declaration of `Definition` and then they'd be no reason to use `and` on any of them. – Samuel Aug 22 '11 at 23:21
15

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

Mark H
  • 13,471
  • 4
  • 26
  • 45