6.3.90.900
:match
(require colon-match) | package: colon-match |
syntax
(:match val-expr clause ...)
clause = [pat body ...+] | [pat (=> id) body ...+] | [pat #:when cond-expr body ...+]
like match, except that it allowes identifiers with colons in patterns to specify types.
For example the pattern x:num is equivalent to the pattern (? number? x).
(:match val-expr [pat body-stuff ...] ...) expands to (match val-expr [(:pat pat) body-stuff ...] ...).
Examples:
> (require colon-match)
> (:match 1 [n:num n]) 1
> (:match 'x [n:num n] [_ #f]) #f
> (:match '(1 2 3) [(list a:num b:num c:num) (+ a b c)]) 6
> (:match '(sym "str" 3) [(list-no-order n:num str:str sym:sym) (list n str sym)]) '(3 "str" sym)
match expander
(:pat pat)
a match expander that rewrites pat to change all of the identifiers written in colon notation
to a pattern that checks the type.
A pattern of the form id:type is rewritten to (type id), and then type is is a match expander that expands to something like (? type? id). This means that you can define your own ":match classes" by defining them as match expanders.
Examples:
> (require colon-match racket/match racket/contract/base (for-syntax racket/base))
> (match '(1 2 3) [(:pat (list a:num b:num c:num)) (+ a b c)]) 6
> (match '(1 2 3) [(list (:pat a:num) _ _) a]) 1
> (define-match-expander pos-num (syntax-rules () [(pos-num id) (? (and/c number? positive?) id)]))
> (match 1 [(:pat x:pos-num) x]) 1
> (match -1 [(:pat x:pos-num) x] [_ #f]) #f
> (:match 1 [x:pos-num x]) 1
syntax
(define-:match-class id pred-expr)
defines id as a match expander that checks that the pattern satisfies pred-expr.
id can then be used in a colon-notation pattern.
Examples: