12 Pattern Matching
The match form supports pattern matching on arbitrary Racket values, as opposed to functions like regexp-match that compare regular expressions to byte and character sequences (see Regular Expressions).
(match target-expr [pattern expr ...+] ...)
The match form takes the result of target-expr and tries to match each pattern in order. As soon as it finds a match, it evaluates the corresponding expr sequence to obtain the result for the match form. If pattern includes pattern variables, they are treated like wildcards, and each variable is bound in the expr to the input fragments that it matched.
Most Racket literal expressions can be used as patterns:
| ||||
'two | ||||
| ||||
'no | ||||
| ||||
'string |
Constructors like cons, list, and vector can be used to create patterns that match pairs, lists, and vectors:
| |||
'two | |||
| |||
'pair | |||
| |||
'vector |
A constructor bound with struct also can be used as a pattern constructor:
> (struct shoe (size color)) | |||
> (struct hat (size style)) | |||
| |||
"top" |
Unquoted, non-constructor identifiers in a pattern are pattern variables that are bound in the result expressions:
| |||
2 | |||
| |||
3 | |||
| |||
23 |
An ellipsis, written ..., act like a Kleene star within a list or vector pattern: the preceding sub-pattern can be used to match any number of times for any number of consecutive elements of the list of vector. If a sub-pattern followed by an ellipsis includes a pattern variable, the variable matches multiple times, and it is bound in the result expression to a list of matches:
| |||
'ones | |||
| |||
'other | |||
| |||
'(2 3) | |||
| |||
45 |
Ellipses can be nested to match nested repetitions, and in that case, pattern variables can be bound to lists of lists of matches:
| ||
'((1) (2 2) (3 3 3)) |
The quasiquote form (see Quasiquoting: quasiquote and ` for more about it) can also be used to build patterns. While unquoted portions of a normal quasiquoted form mean regular racket evaluation, here unquoted portions mean go back to regular pattern matching.
So, in the example below, the with expression is the pattern and it gets rewritten into the application expression, using quasiquote as a pattern in the first instance and quasiquote to build an expression in the second.
| |||
'((lambda (x) (+ x 1)) 1) |
For information on many more pattern forms, see racket/match.
Forms like match-let and match-lambda support patterns in positions that otherwise must be identifiers. For example, match-let generalizes let to a destructing bind:
| ||
'(3 2 1) |
For information on these additional forms, see racket/match.
Pattern Matching in Reference: Racket provides more on pattern matching.