Search code examples
.netf#functional-programmingdiscriminated-union

Mutually referring cases in Discriminated Unions allowed in F#?


The following discriminated union fails to compile:

type Expression =
  | Identifier of string
  | Integer of int
  | Assignment of Identifier * Expression

with the shown error being

The type "Identifier" is not defined.

on the last union case.

I've tried tagging Expression with the rec attribute but that seems of no avail.

Is there a work-around for this? Better yet, is the referred reason the cause of my trouble?


Solution

  • You cannot do that. Inside the Union you cannot refer to another Union element.

    So it should be:

    type Expression =
      | Identifier of string
      | Integer of int
      | Assignment of Expression * Expression
    

    So that when you parse the assignment union you can put a validation there that the first Expression in the tuple should be Identifier.