Unions
Tagged unions are the main way to achieve polymorphism in niva.
Unions are types that can be represented by one of several options at a time.
Declaration of union is like declaration of type
+ switch
Pattern match
To work with a union, you first need to understand what form it is in.
Switch syntax is used for this.
Exhaustive
If you don't check all form options, this will be a compile time error.
Instantiate
It is impossible to instantiate the root of the union, since then it is not clear what form it will correspond to.
But you can create branches, each union branch is no different from a regular type declaration.
Single line syntax
Fields for Roots
Unlike other ML languages, union roots can contain fields
Both Student
and Teacher
have a name
field here.
This simplifies 2 things at once:
There is no need to repeat common fields for each union's branch.
You don't need to pattern match the Person to gain access to the
name
field
Include one union into another
Now Vehicle is Car | Plane | Ship or RaceCar | Truck | PassengerCar | Plane | Ship
So now u can pattern match it like
Inside Car branch we can match each Car branch:
Or the last variant - plain match on every branch:
IDE support
You can try to send match
message to any value of union root type to generate all the branches for pattern matching.
Or match deep to generate matching for every possible nested branch too, like in the last example
Homework
Create a well known example with Cat Dog, all of them are Animal. Animal can eat food. Food are Meat or Vegetable