15 Exhaustive matching
In previous examples we have checked for each possibility, in our
switch statements, but we don't have to:
string var_name1(exp e)
{
switch e {
case Var[x]: return x;
// matches any x
case x: return "not variable";
}
}
string var_name2(exp e)
{
switch e {
case Var[x]: return x;
}
}
var_name2
would raise Match_failure
exception if any
pattern didn't match.
However it is matter of good style, to always check each possibility.
Compiler will warn you, if you fail to do it. This warning comes in
very handy in some situations. For example, suppose you have union
similar to exp
(from example above) in your symbolic algebra
package. Now, you want to add power operator. So you add:
*[exp, int] Pow;
to exp
definition. Now you have to change each pattern matching
of exp
to check for power function. gontc will help you,
complaining about non-exhaustive pattern matching. I, personally, found
similar features in Caml compiler very useful during Gont development.
Whenever I want to add new feature to Gont, I add it to syntax tree
definition and fix compiler, until there are no warnings about
non-exhaustive pattern matching.