Pattern matching

From Reia

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, you can "splat" a variable with an asterisk:

>> 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

Splatting variables is particularly useful when using the "case" flow control statement:

>> foo = 42
42
>> case (42, 1.61803)
..   (*foo, phi):
..     (~yay, foo, phi)
..   else:
..     ~boo
..
(~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 foo isn't splatted:

>> foo = 69
69
>> case (42, 1.61803)
..   (foo, phi):
..     (~yay, foo, phi)
..   else:
..     ~boo
..
(~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, because it isn't splatted.

A final example:

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

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

Personal tools