Pattern Matching
;; Wright–Cartwright–Shinn `match` (Guile: (ice-9 match); Chibi: (chibi match); CHICKEN egg: matchable; Racket: racket/match)
(use-modules (ice-9 match)) ; Guile
(define (area shape)
(match shape
(('circle r) (* 3.14159 r r))
(('rect w h) (* w h))
(('square s) (* s s))
(_ (error "unknown shape" shape))))
(area '(rect 3 4)) ; 12
(match '(1 (2 3) 4)
((a (b c) d) (+ a b c d))) ; 10
(match '(1 2 3 4)
((first second . rest) rest)) ; (3 4)
(match '(1 2 3)
((x ...) (apply + x))) ; 6: ellipsis patterns
(match 5
((? number? n) (* n n))) ; 25: predicate patterns
(match '(add 1 2)
(('add x y) (+ x y))
(('neg x) (- x))) ; 3
;; An expression evaluator using match
(define (evaluate e)
(match e
((? number?) e)
(('+ a b) (+ (evaluate a) (evaluate b)))
(('* a b) (* (evaluate a) (evaluate b)))
(('- a) (- (evaluate a)))))
(evaluate '(+ 1 (* 2 3))) ; 7