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?
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With