UNB/ CS/ David Bremner/ teaching/ cs4613/ tutorials/ Pattern Matching with match

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

Prerequisites
recursion, tests
    (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)))
  (module+ test
    (require rackunit)
    (check-equal? (list-length '(1 2 3)) 3)
    (check-equal? (list-length '()) 0))
    (define (my-map2 f lst)
      (match lst
        ['() '()]
        [(list head tail ...) (cons (f head)
                                    (my-map2 f tail))]))
  (module+ test
    (require rackunit)
    (check-equal? (list-length2 '(1 2 3)) 3)
    (check-equal? (list-length2 '()) 0))