Pattern matching
Pattern matching is a generalization of C language or Java's switch
statement. In C language and Java, the switch
statement only allows you to choose from many statements based on an integer (including char
) or an enum
value. While in Opa, pattern matching is more powerful than that. The more general syntax for pattern matching is:
match(<expr>){ case <case_1>: <expression_1> case <case_2>: <expression_2> case <case_n>: < expression_n> }
When a pattern is executed, <expr>
is evaluated to a value, which is then matched against each pattern in order until a case is found. You can think about it this way:
if (case_1 matched) expression_1 else { if (case_2 matched) expression_2 else { ... if (case_n matched) expression_n else no_matches ... } }
The rules of pattern matching are simple and are as follows:
Rule 1: Any value matches the pattern
_
Rule 2: Any value matches the variable pattern
x
, and the value...