12 Pattern matching tuples
Patterns can include variables. case clause assigns values
found in given place in pattern to them. For example, following function
return first element of tuple passed to it:
int first(*[int, int] t)
{
switch t {
case [x, y]: return x;
}
}
We can mix variables and constants (often called type constructors
in this context) together:
int special_sym(int a, int b)
{
switch [a, b] {
case [_, -1]:
return -1;
case [-1, x]:
return x;
case [x, y]:
return x + y;
}
}
As said before, ``_
'' is match-all pattern. It matches any value.
One might note, that x
also matches any value. However, it is matter
of good style, to use _
when you are not going to use value
matched.
Important thing to note about the example above, is that we construct
tuple, just to pattern-match it. The same result could be achieved with
few if's, but pattern matching is often more readable (at least
when one get used to it :-)
Variables inside patterns are l-values. It means they can be used on
the left hand side of assignment operator. In fact, there would be
no way of changing content of tuple without it :)
For example, following function exchanges sides of pair passed as argument:
void swap_pair(*['a, 'a] p)
{
switch p {
case [x, y];
'a tmp = x;
x = y;
y = x;
}
}
12.1 Changing top-level pattern
Consider following code:
switch 10 {
case x:
x = 5; // what to change?
}
Because of this, it is not allowed to change top-level pattern
variable.