Unions
Declaring unions
While a record stores all of the values declared in it,
a union will store only one of the choices available.
This is useful for a value that can have one of several non-overlapping states.
Long unions
As with records, you can put the members on their own lines instead of in parentheses.
Creating union values
Declaring the union generates functions verified-id age(a nat) and no-id age().
Getting union values
Declaring the union also generates a function verified-id nat?(a age)
(not used in the above example).
This works like a record field getter, but the result is optional since the union might not have that member.
Matching on union values
The match expression handles each possibility of a union.
Like an if expression, each branch is an expression
with the same type as the whole match.
If a member has a value, it must be declared after the name,
like x in as verified-id x.
This uses the same destructuring syntax as for locals.
(So to ignore a value, use _.)
An else branch is required when matching on a union unless all cases are handled.
(This is explicit to avoid accidentally forgetting a case.)
Matching on other values
You can also match on other types:
-
String-like types:
symbol,string,char8 array,char8[]char32 array,char32[]. -
Integral types:
nat8,nat16,nat32,nat64,int8,int16,int32,int64.
A match on these types has an implicit
else just like for an if.