On this page:

3.13 Dispatch: case


(case val-expr case-clause ...)

case-clause = [(datum ...) then-body ...+]
  | [else then-body ...+]
Evaluates val-expr and uses the result to select a case-clause. The selected clause is the first one with a datum whose quoted form is equal? to the result of val-expr. If no such datum is present, the else case-clause is selected; if no else case-clause is present, either, then the result of the case form is #<void>.

The case form of racket differs from that of R6RS: Scheme or R5RS: Legacy Scheme by being based equal? instead of eqv? (in addition to allowing internal definitions).

For the selected case-clause, the results of the last then-body, which is in tail position with respect to the case form, are the results for the whole case form.

A case-clause that starts with else must be the last case-clause.

The case form can dispatch to a matching case-clause in O(log N) time for N datums.

> (case (+ 7 5)
   [(1 2 3) 'small]
   [(10 11 12) 'big])


> (case (- 7 5)
   [(1 2 3) 'small]
   [(10 11 12) 'big])


> (case (string-append "do" "g")
   [("cat" "dog" "mouse") "animal"]
   [else "mineral or vegetable"])


> (case (list 'y 'x)
   [((a b) (x y)) 'forwards]
   [((b a) (y x)) 'backwards])


> (case 'x
   [(x) "ex"]
   [('x) "quoted ex"])


> (case (list 'quote 'x)
   [(x) "ex"]
   [('x) "quoted ex"])

"quoted ex"


(define (classify c)
  (case (char-general-category c)
   [(ll lu lt ln lo) "letter"]
   [(nd nl no) "number"]
   [else "other"]))


> (classify #\A)


> (classify #\1)


> (classify #\!)