Scheme Medium · Lesson 1 · On the house

Pattern matching with ice-9 match

Destructure lists, pairs and trees with match; use predicates, or-patterns, ellipsis and dotted tails in one expression. Lesson 1 is free — on the house.

Lessons · Scheme Medium · Lesson 1 of 10 · On the house

Pattern matching with ice-9 match

Destructure lists, pairs and trees with match; use predicates, or-patterns, ellipsis and dotted tails in one expression.

Illustration for Scheme
Lesson 1 is on the house.

(ice-9 match) turns nested conditionals into one match form. Patterns are tried top to bottom; the first match runs its body. A final _ catches anything you did not name.

A list pattern (a b . rest) binds the first two cars and the remaining cdr. Quoted literals such as 'add must appear exactly, so (match '(add 2 3) (('add a b) (+ a b))) returns 5.

(or p1 p2 …) succeeds if any subpattern matches. (? pred? x) matches when (pred? value) is true and binds x to that value, as with (? string? s) or (? number? n).

Ellipsis after a subpattern collects repetitions: ((keys . vals) ...) on an alist yields parallel lists of keys and values. Combine that with cons to rebuild structured results.

Recursive helpers shine on trees. tree-sum matches a number, else a pair whose car and cdr are summed, else 0. That walks improper trees such as ((1 2) (3 . 4)) without nested if chains.

Keep patterns specific first and catch-alls last. Prefer match over a tower of car/cdr checks whenever the shape of the data is what decides the branch.

match

(use-modules (ice-9 match))
(display (match '(add 2 3)
  (('add a b) (+ a b))
  (('mul a b) (* a b))
  (_ 0)))
(newline)
(display (match '(1 2 3 4)
  ((a b . rest) (list a b rest))))
(newline)
(display (match 4
  (1 'one)
  ((or 2 4 6) 'even-small)
  (_ 'other)))
(newline)
(display (match '((x . 1) (y . 2))
  (((keys . vals) ...) (cons keys vals))))
(newline)
(define (tree-sum t)
  (match t
    ((? number? n) n)
    ((a . b) (+ (tree-sum a) (tree-sum b)))
    (_ 0)))
(display (tree-sum '((1 2) (3 . 4))))
(newline)
(display (match "hi"
  ((? string? s) (string-length s))
  (_ 0)))
(newline)
Match this when you type.

Quiz

What does (match '(add 2 3) (('add a b) (+ a b)) (_ 0)) return?

Quiz

In ((keys . vals) ...), what does ... collect?

Quiz

What does (? string? s) require?

Quiz

What is _ in a match clause?

Check

Match the still for: Pattern matching with ice-9 match.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.