1.15. Unions

Felix supports unions, but they are a bit different to C unions. A union is a way of merging a finite set of types into a single type; that is, it provides type unification. An object of a union type consists of a tag, identifying what type the component has, and the actual component. Here are some examples of unions.
Start C++ section to tut/examples/tut117.flx[1 /1 ]
     1: include "std";
     2: 
     3: union parity =
     4:   | Odd
     5:   | Even
     6: ;
     7: 
     8: union int_option =
     9:   | Some of int
    10:   | None
    11: ;
    12: 
    13: enum E {zero, one, two};
    14: 
    15: val x = Odd;
    16: val y = Some 1;
    17: val z = one;
    18: 
End C++ section to tut/examples/tut117.flx[1]
We'll see how to actually use unions in the next section. But note first that the parity example is very similar to a C enumeration. The names of the union components are called constructors by convention. They have two roles: they represent the constant value of the tag indicating which component we're talking about: tags values are assigned sequentially, starting at 0.

In their second role, the constructors are considered functions, so that Some is a function with type:

  int -> int_option
It is important to note that the constructor names are visible in the enclosing space, unlike struct component names.

The enum form only permits constant constructors (ones with no arguments), values are not permitted.