Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can discriminated unions refer to each other?

I'm building an expression tree using discriminated unions. The below code:

type IntExpression =
    | TrueIsOne of BoolExpression

type BoolExpression =
    | LessThan of IntExpression * IntExpression
    | And of BoolExpression * BoolExpression
    | Or of BoolExpression * BoolExpression
    | Bool of bool

throws an error because BoolExpression is not defined. Swapping the definitions just results in the reverse (IntExpression is not defined) as you would expect.

Is there a way around this?

like image 806
mavnn Avatar asked Jul 22 '10 12:07

mavnn


People also ask

How is a discriminated union defined?

Discriminated unions are useful for heterogeneous data; data that can have special cases, including valid and error cases; data that varies in type from one instance to another; and as an alternative for small object hierarchies. In addition, recursive discriminated unions are used to represent tree data structures.

What is discriminated unions in TypeScript?

The concept of discriminated unions is how TypeScript differentiates between those objects and does so in a way that scales extremely well, even with larger sets of objects. As such, we had to create a new ANIMAL_TYPE property on both types that holds a single literal value we can use to check against.

Are the unions of F# discriminated briefly explain?

In F#, a sum type is called a “discriminated union” type. Each component type (called a union case) must be tagged with a label (called a case identifier or tag) so that they can be told apart (“discriminated”). The labels can be any identifier you like, but must start with an uppercase letter.

What is a tagged union C++?

Simply put, tagged unions are unions that have associated with them a piece of data that tracks which of the potential union properties is currently set. In C++ you can choose between structs and classes to encapsulate the union, or develop your own custom data structure base solution (like a map).


1 Answers

Yes, use and to group type definitions with inter-dependencies:

type IntExpression =
    | TrueIsOne of BoolExpression

and BoolExpression =
    | LessThan of IntExpression * IntExpression
    | And of BoolExpression * BoolExpression
    | Or of BoolExpression * BoolExpression
    | Bool of bool
like image 120
Mau Avatar answered Jan 03 '23 12:01

Mau