<- ^ ->
Pattern matching tuples

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 not l-values, therefore tuples are immutable, i.e. one cannot modify them after they have been constructed.

<- ^ ->
Pattern matching tuples