One very useful feature of racket is pattern matching. This is used
in syntax-case
to define macros, but also in more familiar function
definitions using match.
Roughly speaking, you can think about match
as fancy cond
, where
instead of specifying a test for each case, you specify a pattern to
match against the data.
map
using match
- Compare the following implementation of
my-map
with the definition in recursion.
(define (my-map f lst)
(match lst
['() '()]
[(cons head tail) (cons (f head)
(my-map f tail))]))
(module+ test
(require rackunit)
(check-equal? (my-map sub1 '(1 2 3)) '(0 1 2)))
- Use
match
to impliment alist-length
function that passes the following tests
(module+ test
(require rackunit)
(check-equal? (list-length '(1 2 3)) 3)
(check-equal? (list-length '()) 0))
- A common racket idiom is to use the
...
"collector pattern" instead ofcons
. This is also useful insyntax-case
in macros.
(define (my-map2 f lst)
(match lst
['() '()]
[(list head tail ...) (cons (f head)
(my-map2 f tail))]))
- Use
match
and a a collector pattern to impliment alist-length2
function that passes the following tests
(module+ test
(require rackunit)
(check-equal? (list-length2 '(1 2 3)) 3)
(check-equal? (list-length2 '()) 0))