Matching
Variant types being, in essence, the disjunctive union of cases akin to types, values of such types need to be examined case by case: this is what pattern matching does.
Here is a function that transforms a colour variant type to an integer.
Note: The
when
-clauses must cover all the variants of the typecolour
. When the constructor has no argument, which is equivalent to having a[]
(unit) argument, it can be omitted, hencewhen(Default)
instead ofwhen(Default())
.
The right-hand sides of each when
-clause is an expression. Sometimes
we might need statements to be processed before a value is given to
the clause. In that case, the do
expression comes handy. It enables
the opening of a block of statements like a function body, that is, a
block ended with a return
statement whose argument has the value of
the block, like so:
Another example is matching on whether an integer is a natural number or not: