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.

main void() info log "{15.verified-id is-adult}" info log "{60.verified-id is-adult}" info log "{no-id is-adult}" age union(verified-id nat, no-id) is-adult bool(a age) match a as verified-id x x >= 18 as no-id false

Long unions

As with records, you can put the members on their own lines instead of in parentheses.

age union verified-id nat no-id

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.

main void() info log ("chocolate" order 1) info log ("pizza" order 2) order string(a string, count nat) plural = a plural count if c ?= a condiment "{plural} with {c}" else plural condiment string?(a string) match a as chocolate "peanut butter", as "french fries" "ketchup", plural string(a string, count nat) match count as 0 "no {a}s" as 1 "one {a}" else "{count} {a}s"