1 Welcome to PLT Scheme
2 Scheme Essentials
3 Built-In Datatypes
4 Expressions and Definitions
5 Programmer-Defined Datatypes
6 Modules
7 Contracts
8 Input and Output
9 Regular Expressions
10 Exceptions and Control
11 Iterations and Comprehensions
12 Pattern Matching
13 Classes and Objects
14 Units (Components)
15 Reflection and Dynamic Evaluation
16 Macros
17 Performance
18 Running and Creating Executables
19 Compilation and Configuration
20 More Libraries
Bibliography
Index
Version: 4.0.2

 

4.12 Simple Dispatch: case

The case form dispatches to a clause by matching the result of an expression to the values for the clause:

(case expr

  [(datum ...+) expr ...+]

  ...)

Each datum will be compared to the result of the first expr using eqv?. Since eqv? doesn’t work on many kinds of values, notably symbols and lists, each datum is typically a number, symbol, or boolean.

Multiple datums can be supplied for each clause, and the corresponding expr is evaluated of any of the datums match.

Examples:

  > (let ([v (random 6)])

      (printf "~a\n" v)

      (case v

        [(0) 'zero]

        [(1) 'one]

        [(2) 'two]

        [(3 4 5) 'many]))

  3

  many

The last clause of a case form can use else, just like cond:

Examples:

  > (case (random 6)

      [(0) 'zero]

      [(1) 'one]

      [(2) 'two]

      [else 'many])

  many

For more general pattern matching, use match, which is introduced in Pattern Matching.