[next] [prev] [prev-tail] [tail] [up]

### 6.9 Pattern matching

Any time you define a name, you can use a pattern instead. For example:

[fred, petra] = [12, 13]

defines fred to have the value 12 and petra to have the value 13.

A pattern describes the structure you are expecting for the value. When the value is computed it is matched against the pattern and, if the match is successful, the names in the pattern are bound to those parts of the value. Our example is exactly equivalent to:

temp = [12, 13]; fred = temp?0, is_list temp && is_list_len 2 temp = error "pattern match failed"; petra = temp?1, is_list temp && is_list_len 2 temp = error "pattern match failed";

where temp is an invisible, anonymous symbol.

You can pattern match on any of nip2’s data structures and types. You can use:

a:b
  Tests for the value being a non-empty list and then assigns a to the head and b to the tail.
(a,b)
  Tests for the value being a complex and then assigns a to the real part and b to the imaginary.
[a,b,c]
  Tests for the value being a list of length three and then assigns a, b and c to the three elements.
(class - name b)
  Tests for the value being an instance of the named class, then assigns b to that class instance.
constant
  Tests for the value being equal to that constant. Constants are things like "hello world" or 12.

You can nest patterns in any way you like. Patterns are useful in conjunction with list comprehensions, see §6.6.5.

You can’t use patterns in function arguments in the current version, hopefully this will added shortly.

[next] [prev] [prev-tail] [front] [up]