Variant Types

CKS variant types are also known as “tagged unions” or “disjoint unions”. Functional languages like Haskell and ML/OCaml support them, but unfortunately most C-derived languages do not. They are the natural complement to the record/type.

Let’s define a record type “Person” with three fields:

def Person = {
  Name: String
  Age: Int
  Employed: Bool
}

To create a value of that type, we must provide values for all the fields:

{ Name = "Scooby Doo", Age = 53, Employed = False }

For a variant, you need to provide a value for exactly one of it’s options. So let’s define an example variant type “Contact” with three options:

def Contact = <
  Email: String
  Icq: Int
  Unknown
>

To define a variant value, you need to select one option and supply it’s value. Here are three possible values, one on each line:

Email: "sdoo@mysterymachine.org"
Icq: 129402139
Unknown

Why are variants so useful? Well, for one, they can model C’s “enum” and “union” constructs uniformly. This also means they can model optionality (a more general form of C’s “null pointer” concept).

The best way to see how variants are useful is probably to try them out. Try modeling your data with CKS types and see if you can take advantage of variant types.