Sum types and pattern matching
Futhark supports nonrecursive sum types (sometimes called variants or tagged unions). A sum type indicates one or more
#-prefixed constructors, and for each constructor a payload.
Given a value of a sum type, we use a
match expression to handle each possible case.
There must be a
case for each possible constructor.
Sum type constructors can have any number of payload values, including zero.
Such types are sometimes called enumeration types (or enums), but to Futhark they are the same as sum types.
A common trick is to define a constructor payload as a record in order to imitate named fields.
Like all other types in Futhark, sum types are structurally typed. This means that naming with
type is optional, and we can just inline the type instead:
In practice, this means that we often need to add type annotations to disambiguate which type we mean, as there are an infinite number of possible types with the same constructor. For example, to supplement
dir from before, we can define the following:
When the compiler encounters an expression
#left, how is it supposed to know whether it is of type
dir_3d, or some anonymous type that we have not even bothered naming? The type checker will complain in these cases, and we can solve the problem by adding, for example, a return type annotation to the function.