ZetCode

Scheme pattern matching

last modified November 24, 2026 Guile 3.0

Pattern matching compares a value with a series of patterns that describe its shape and runs the code of the first pattern that fits. Parts of the value are bound to names along the way, so taking a list apart no longer needs chains of car, cdr, and type tests. The patterns look much like those of syntax-rules, but they are applied to data while the program runs. Guile provides pattern matching in the (ice-9 match) module. The examples run with GNU Guile 3.0.7.

A first match

match takes an expression and a list of clauses. Each clause is a pattern followed by the body to evaluate when the pattern matches. The simplest patterns are literal values, which must be equal? to the value.

first.scm
(use-modules (ice-9 match))

(define (describe x)
  (match x
    (0 "zero")
    (1 "one")
    ("yes" "a word of consent")
    ('stop "a stop sign")
    (#t "true")
    (_ "something else")))

(for-each (lambda (x)
            (write x)
            (display " -> ")
            (display (describe x))
            (newline))
          (list 0 1 "yes" 'stop #t 42 'go))

Numbers, strings, and booleans match themselves. A symbol must be quoted, as in 'stop, because a bare name in a pattern is a variable. The underscore _ matches anything and binds nothing, so the last clause catches all other values. The clauses are tried from top to bottom.

$ guile first.scm
0 -> zero
1 -> one
"yes" -> a word of consent
stop -> a stop sign
#t -> true
42 -> something else
go -> something else

Matching lists

A list pattern matches a list with the same number of elements, matching each element against a subpattern. A dotted pattern (x . rest) matches a pair and binds the first element and the rest of the list.

lists.scm
(use-modules (ice-9 match))

(define (shape xs)
  (match xs
    (() "empty")
    ((x) (string-append "one element: " (number->string x)))
    ((x y) (string-append "a pair, sum " (number->string (+ x y))))
    ((x . rest)
     (string-append "starts with " (number->string x)
                    ", " (number->string (length rest)) " more"))))

(for-each (lambda (xs)
            (display (shape xs))
            (newline))
          (list '() '(7) '(3 4) '(1 2 3 4 5)))

(define (sum xs)
  (match xs
    (() 0)
    ((head . tail) (+ head (sum tail)))))

(display (sum '(4 8 15 16 23 42)))
(newline)

(match '(1 (2 3) 4)
  ((a (b c) d)
   (display (list a b c d))
   (newline)))

shape tells lists apart by length: () matches the empty list, (x) a list of one element, and (x y) a list of two. The dotted pattern takes all longer lists. sum is the list-sum procedure of the recursion article written with patterns instead of null?, car, and cdr. Patterns nest, so (a (b c) d) takes apart a list with a sublist in one step.

$ guile lists.scm
empty
one element: 7
a pair, sum 7
starts with 1, 4 more
108
(1 2 3 4)

The ellipsis

An ellipsis ... after a subpattern matches zero or more elements, and the variables of the subpattern are bound to lists. ..1 requires at least one element.

ellipsis.scm
(use-modules (ice-9 match))

(define (average-of record)
  (match record
    ((name score ...)
     (list name (exact->inexact (/ (apply + score) (length score)))))))

(display (average-of '("Eva" 8 9 10)))
(newline)
(display (average-of '("Peter" 6 7)))
(newline)

(define settings '((width 800) (height 600) (title "Editor")))

(match settings
  (((keys vals) ...)
   (display keys)
   (newline)
   (display vals)
   (newline)))

(define (command words)
  (match words
    (("add" items ..1) (list 'adding items))
    (("clear") 'clearing)
    (("add") 'nothing-to-add)
    ((cmd _ ...) (list 'unknown cmd))))

(for-each (lambda (w) (write (command w)) (newline))
          '(("add" "milk" "tea") ("clear") ("add") ("delete" "x" "y")))

In average-of, name takes the first element and score the list of all the others. The pattern ((keys vals) ...) matches a list of two-element lists and collects the first elements into keys and the second into vals, which splits the settings into two columns. In command, items ..1 matches only when something follows "add", so the bare ("add") falls through to its own clause. _ ... ignores any number of arguments.

$ guile ellipsis.scm
(Eva 9.0)
(Peter 6.5)
(width height title)
(800 600 Editor)
(adding ("milk" "tea"))
clearing
nothing-to-add
(unknown "delete")

Tagged data

A list whose first element is a symbol naming its kind is a common way to represent variants in Scheme. A quoted symbol at the start of a pattern selects the variant, and the rest of the pattern takes the fields.

tagged.scm
(use-modules (ice-9 match))

(define pi 3.14159)

(define (area shape)
  (match shape
    (('circle r) (* pi r r))
    (('rect w h) (* w h))
    (('square side) (* side side))
    (('triangle base height) (/ (* base height) 2))))

(define shapes
  '((circle 1) (rect 3 4) (square 5) (triangle 6 2)))

(for-each (lambda (s)
            (write s)
            (display ": ")
            (display (area s))
            (newline))
          shapes)

(define (handle event)
  (match event
    (('key char) (string-append "key " (string char)))
    (('click x y) (string-append "click at " (number->string x)
                                 "," (number->string y)))
    (('quit) "quit")))

(for-each (lambda (e) (display (handle e)) (newline))
          (list (list 'key #\q) '(click 120 45) '(quit)))

area has one clause for each kind of shape, and each clause names the fields it needs. handle processes events of different kinds in the same way. A clause such as ('quit) matches only the one-element list with that symbol. Adding a new kind of shape means adding a clause; a shape with the right tag but the wrong number of fields matches no clause.

$ guile tagged.scm
(circle 1): 3.14159
(rect 3 4): 12
(square 5): 25
(triangle 6 2): 6
key q
click at 120,45
quit

Predicates

Several pattern forms test values instead of their shape. (? pred pat ...) matches when the predicate returns true and the value also matches the optional patterns. (= proc pat) applies a procedure and matches its result. and, or, and not combine patterns.

predicates.scm
(use-modules (ice-9 match))

(define (classify x)
  (match x
    ((? integer? (? negative?)) "negative integer")
    ((and (? integer?) (? even?)) "even integer")
    ((? integer? n) (string-append "odd integer " (number->string n)))
    ((? number?) "other number")
    ((? string? (= string-length len))
     (string-append "string of " (number->string len)))
    ((or 'yes 'no) "answer")
    ((not (? pair?)) "atom")
    ((= car (? symbol? head)) (string-append "list headed by "
                                             (symbol->string head)))
    (_ "list")))

(for-each (lambda (x)
            (write x)
            (display " -> ")
            (display (classify x))
            (newline))
          (list -3 10 7 2.5 "tatra" 'yes #\a '(go 1) '(1 2)))

(? integer? (? negative?)) needs both tests to pass; the same can be written with and, as in the second clause. In (? integer? n), the variable n is bound to the tested value. The string clause measures the string with (= string-length len) and binds the length. (or 'yes 'no) matches either symbol, (not (? pair?)) matches every value that is not a pair, and (= car (? symbol? head)) checks the first element of a list. A predicate can be any procedure, including a lambda.

$ guile predicates.scm
-3 -> negative integer
10 -> even integer
7 -> odd integer 7
2.5 -> other number
"tatra" -> string of 5
yes -> answer
#\a -> atom
(go 1) -> list headed by go
(1 2) -> list

Repeated variables and failure

A variable that appears twice in a pattern must match equal? values in both places. A clause can also give up after it has matched: the form (=> name) after the pattern binds a procedure that continues with the next clause.

repeated.scm
(use-modules (ice-9 match))

(define (relation pair)
  (match pair
    ((x x) "equal")
    ((x y) (=> next)
     (if (< x y) "ascending" (next)))
    ((x y) "descending")))

(for-each (lambda (p)
            (write p)
            (display " ")
            (display (relation p))
            (newline))
          '((3 3) (1 5) (9 2) ((a b) (a b))))

(define (palindrome? xs)
  (match xs
    (() #t)
    ((x) #t)
    ((first middle ... first) (palindrome? middle))
    (_ #f)))

(write (map palindrome? '((r a d a r) (1 2 2 1) (1 2 3))))
(newline)

The pattern (x x) matches a pair of equal elements, nested lists included. The second clause of relation matches every pair, but it calls next unless the elements ascend, and matching resumes with the third clause. palindrome? uses a repeated variable around an ellipsis: the pattern (first middle ... first) matches a list whose first and last elements are equal and binds the elements between them.

$ guile repeated.scm
(3 3) equal
(1 5) ascending
(9 2) descending
((a b) (a b)) equal
(#t #t #f)

match-lambda and match-let

A procedure that only matches its argument can be written with match-lambda. match-lambda* matches the list of all arguments, and match-let binds variables by taking values apart.

lambdas.scm
(use-modules (ice-9 match))

(define point-x
  (match-lambda
    ((x _) x)
    (#(x _) x)))

(write (map point-x (list '(3 4) #(5 6))))
(newline)

(define distance
  (match-lambda*
    (((x1 y1) (x2 y2))
     (sqrt (+ (expt (- x2 x1) 2) (expt (- y2 y1) 2))))
    (((x y))
     (sqrt (+ (* x x) (* y y))))))

(write (distance '(1 1) '(4 5)))
(newline)
(write (distance '(6 8)))
(newline)

(match-let (((name . rest) '("Jana" 34 "Zilina"))
            ((x y) '(10 20)))
  (write (list name rest (+ x y)))
  (newline))

(define orders '(("tea" 2 3/2) ("cake" 1 4) ("water" 3 1)))

(write (map (match-lambda ((item qty price) (* qty price))) orders))
(newline)

point-x accepts a point given as a list or as a vector. distance matches its argument list, so it computes the distance between two points or from the origin depending on how many points it receives. match-let works like let with patterns in place of names. match-lambda is also convenient as the argument of map, where it names the fields of each order. Guile 3.0.7 also has match-let* and match-letrec.

$ guile lambdas.scm
(3 5)
5
10
("Jana" (34 "Zilina") 30)
(3 4 3)

Records and vectors

The pattern ($ type pat ...) matches a record of the given type and matches its fields in the order of the constructor. A pattern written as a vector #(pat ...) matches a vector.

records.scm
(use-modules (ice-9 match) (srfi srfi-9))

(define-record-type <employee>
  (make-employee name role salary)
  employee?
  (name employee-name)
  (role employee-role)
  (salary employee-salary))

(define staff
  (list (make-employee "Zuzana" 'developer 3200)
        (make-employee "Marek" 'manager 4100)
        (make-employee "Ivan" 'developer 2900)))

(define (title e)
  (match e
    (($ <employee> name 'manager _)
     (string-append name ", manager"))
    (($ <employee> name role (? (lambda (s) (> s 3000))))
     (string-append name ", senior " (symbol->string role)))
    (($ <employee> name role _)
     (string-append name ", " (symbol->string role)))))

(for-each (lambda (e) (display (title e)) (newline)) staff)

(define (corner v)
  (match v
    (#(x y) (list 'point x y))
    (#(x y z) (list 'point3d x y z))
    (#(x ...) (list 'elements (length x)))))

(for-each (lambda (v) (write (corner v)) (newline))
          (list #(1 2) #(1 2 3) #(1 2 3 4 5)))

The first clause of title matches managers by the quoted symbol in the role field. The second tests the salary with a lambda predicate, and the third takes the remaining employees. The fields are matched by position, so all three are listed in each pattern. Vector patterns must match the length of the vector unless they end with an ellipsis, as in the last clause of corner.

$ guile records.scm
Zuzana, senior developer
Marek, manager
Ivan, developer
(point 1 2)
(point3d 1 2 3)
(elements 5)

No matching pattern

When no clause matches, match signals an error. A _ clause at the end prevents this when there is a sensible default.

nomatch.scm
(use-modules (ice-9 match))

(define (area shape)
  (match shape
    (('circle r) (* 3.14159 r r))
    (('rect w h) (* w h))))

(display (area '(rect 2 3)))
(newline)
(display (area '(triangle 1 2 3)))
(newline)

The first call finds the rectangle. A triangle matches neither clause, and Guile stops with a match-error that shows the value. The position points to the match form inside area. The backtrace is omitted from the output.

$ guile nomatch.scm
6
nomatch.scm:4:2: In procedure area:
Throw to key `match-error' with args `("match" "no matching pattern" (triangle 1 2 3))'.

Simplifying expressions

Pattern matching is at its best on tree-shaped data such as code. The last example differentiates arithmetic expressions written as Scheme lists and simplifies the result with rewriting rules.

simplify.scm
(use-modules (ice-9 match))

(define (simplify e)
  (match e
    (((and op (or '+ '*)) a b)
     (simplify-step (list op (simplify a) (simplify b))))
    (_ e)))

(define (simplify-step e)
  (match e
    (('+ 0 x) x)
    (('+ x 0) x)
    (('* 0 _) 0)
    (('* _ 0) 0)
    (('* 1 x) x)
    (('* x 1) x)
    (((and op (or '+ '*)) (? number? a) (? number? b))
     (if (eq? op '+) (+ a b) (* a b)))
    (_ e)))

(define (derive e var)
  (match e
    ((? number?) 0)
    ((? symbol?) (if (eq? e var) 1 0))
    (('+ a b) `(+ ,(derive a var) ,(derive b var)))
    (('* a b) `(+ (* ,a ,(derive b var)) (* ,(derive a var) ,b)))))

(define (show label e)
  (display label)
  (write e)
  (newline))

(define f '(+ (* 3 (* x x)) (+ (* 2 x) 7)))

(show "f      = " f)
(show "raw f' = " (derive f 'x))
(show "f'     = " (simplify (derive f 'x)))
(show "g      = " (simplify '(* (+ 1 1) (+ y (* 0 z)))))

derive applies the rules of differentiation: a constant gives 0, the variable gives 1, and sums and products follow the sum and product rules. Its results are built with quasiquote and are correct but cluttered. simplify works bottom-up: it simplifies the operands first and then applies simplify-step. The pattern (and op (or '+ '*)) binds the operator while restricting it to the two symbols. The rules remove additions of 0 and multiplications by 1, turn products with 0 into 0, and compute operations on two numbers. Each rule is one line, which makes the rewriting easy to read and to extend.

$ guile simplify.scm
f      = (+ (* 3 (* x x)) (+ (* 2 x) 7))
raw f' = (+ (+ (* 3 (+ (* x 1) (* 1 x))) (* 0 (* x x))) (+ (+ (* 2 1) (* 0 x)) 0))
f'     = (+ (* 3 (+ x x)) 2)
g      = (* 2 y)

Source

Pattern Matching — GNU Guile Reference Manual

In this article we have matched literals, lists, and dotted pairs, collected elements with the ellipsis, dispatched on tagged lists, tested values with predicates and and, or, and not, used repeated variables and the failure continuation, written procedures with match-lambda, taken apart records and vectors, seen the error for an unmatched value, and simplified symbolic derivatives. The macros with syntax-rules article applies a similar pattern language to code, and the pairs and lists article covers the data most patterns take apart.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.