Pattern matching

From Reia

Revision as of 21:22, 21 February 2010 by Tony (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

Assignment

The = operator can be used for simple assignment:

>> foo = 42
42

...but it can also be used for compound assignment using patterns:

>> (foo, [bar, baz]) = (1, [2, 3])
(1,[2,3])
>> foo
1
>> bar
2
>> baz
3

From this example, you hopefully see that the "equals" operator does much more than just simple assignment. Rather, it matches expressions using patterns, and specifying a single variable as a pattern is the degenerate case.

This example binds the variables foo, bar, and baz to the values 1, 2, and 3 respectively. All variables on the left side will be assigned, regardless of whether or not they're bound. To override this behavior, the unary ^ operator can be used:

>> foo = 42
42
>> (^foo, [bar, baz]) = (1, [2, 3])
NoMatch: right hand side value 1

This example will raise a NoMatch exception, because foo does not match the respective variable 1.

Case statement

Ordinarily variables are rebound in a pattern matching context. However, using the ^ unary operator, the values variables are bound to become part of a pattern, and the variables themselves won't be rebound:

>> foo = 42
42
>> case (42, 1.61803)
.. when (^foo, phi)
..   (:yay, foo, phi)
.. else
..   :boo
.. end
..
=> (:yay, 42, 1.61803)

From this example, you can see the case statement matches statements using patterns. The expressions at one level of indentation are patterns. The value in the first slot of the tuple is compared against the value of foo, and if it matches, phi is bound, in this case to the value in its respective slot of the tuple, which is 1.61803.

Here's another example where the ^ operator isn't used:

>> foo = 69
69
>> case (42, 1.61803)
.. when (foo, phi)
..   (:yay, foo, phi)
.. else
..   :boo
.. end
..
=> (:yay, 42, 1.61803)

In this example, foo is bound to 42 and phi is bout to 1.61803. The original value of foo is overwritten.

A final example:

>> foo = 69
69
>> case (42, 1.61803)
.. when (^foo, phi)
..   (:yay, foo, phi)
.. else
..   :boo
.. end
..
=> :boo

In this example, the specified pattern failed to match the one given to the case statement, since foo is not equal to 42.