A pattern matching macro for (Chez Scheme)
p ::= _
| ()
| ,x
| ,(sat? x)
| ,(sat?)
| (tag ,x y ...) -- record-type
| (pcar ... . rest)
| (pcar . pcdr)
| symbol
| datum
- The wildcard
_
can be used to match anything. - The pattern
,x
matches anything as well, and binds the corresponding value tox
.
,(sat?)
matches a value that satisfied the condition sat?.,(sat? x)
matches a value that satisfied the condition sat? and binds it tox
.
symbol & datum are other patterns, and will be matched as literals.
-
matching a list
code
(match '(x y z 1 2 3 . end) [(,(symbol? syms) ... ,rest ... . end) (printf "syms: ~a\n" syms) (printf "rest: ~a\n" rest)])
output
syms: (x y z) rest: (1 2 3)
-
matching list of lists
code
(match '(let-values ([(x y z) (values 1 2 3)] [(a b c) (values 'a 'b 'c)]) (list a b c x y z)) [(let-values ([(,(symbol? vars) ...) ,exps] ...) ,body ...) (printf "~a\n" `(let-values ,vars ,exps ,body))])
output
(let-values ((x y z) (a b c)) ((values 1 2 3) (values 'a 'b 'c)) ((list a b c x y z)))
code
(match '(1 2 3 1 2 3 (1 2 3)) [(,x ... ,y ... (,z ...)) (printf "x=~a, y=~a, z=~a\n" x y z)])
output
x=(1 2 3 1 2 3), y=(), z=(1 2 3)
-
Same values
code
(match '(1 1 (1)) [(,x ,x (,x)) (printf "x=~a\n" x)])
output
x=1
-
Same lists
code
(match '(1 2 3 (1 2 3)) [(,x ... (,x ...)) (printf "x=~a\n" x)])
output
x=(1 2 3)
code
(match '(1 2 3 1 2 3 (1 2 3)) [(,x ... ,x ... (,x ...)) (printf "x=~a\n" x)])
output
x=(1 2 3)
Suppose the following record-type is provided.
(define-record-type point (fields x y))
-
code
(match (make-point 1 2) [(point 1 2) #t])
output
#t
-
code
(match (make-point 1 2) [(point ,x ,y) (+ x y)])
or
(match (make-point 1 2) [(point ,y ,x) (+ x y)])
output
3
-
code
(match (make-point 1 2) [(point ,x 2) x])
or
(match (make-point 1 2) [(point ,x) x])
or
(match (make-point 1 2) [(point ,x _) x])
output
1
-
code
(match (make-point 1 2) [(point 2 ,x) x])
output
Exception in match: duplicated fields found in the record pattern (point 2 ,x)
Type (debug) to enter the debugger.
5. code
```scheme
(match (make-point 1 2)
[(point ,z ,y) y])
output
Exception in match: z is not a field of the record type point
Type (debug) to enter the debugger.
To learn more about the usage, please read the following examples under this directory:
To see what the match statement will expand into, you can use the expand
function to expand the macro.
(parameterize ([print-gensym 'pretty/suffix])
(pretty-print
(expand
'(match exp ...))))
The file interp-with-match.expanded.ss in this directory is generated by the file expand-test.ss, with the file interp-with-match.ss as the input.
To learn more about the implementation, please read the source file match.ss directly.
Currently, nested quasiquote
patterns is not well supported.