3.13 Dispatch: case (original) (raw)

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 acase-clause. The selected clause is the first one with adatum whose quoted form is equal? to the result of val-expr. If no such datum is present, theelse case-clause is selected; if no else case-clause is present, either, then the result of thecase form is #.

The caseform of racket differs from that of R6RS orR5RS by being based on equal? instead of eqv? (in addition to allowing internal definitions).

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

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

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

Examples:

> (case (+ 7 5) [(1 2 3) 'small] [(10 11 12) 'big])
'big
> (case (- 7 5) [(1 2 3) 'small] [(10 11 12) 'big])
'small
> (case (string-append "do" "g") [("cat" "dog" "mouse") "animal"] [else "mineral or vegetable"])
"animal"
> (case (list 'y 'x) [((a b) (x y)) 'forwards] [((b a) (y x)) 'backwards])
'backwards
> (case 'x [(x) "ex"] [('x) "quoted ex"])
"ex"
> (case (list 'quote 'x) [(x) "ex"] [('x) "quoted ex"])
"quoted ex"
> (classify #\A)
"letter"
> (classify #\1)
"number"
> (classify #\!)
"other"
3.13.1 Variants of case🔗

The bindings documented in this section are provided by the racket/case library, not racket/base or racket.

Added in version 8.11.1.8 of package base.

(case/equal val-expr case-clause ...)
(case/equal-always val-expr case-clause ...)
(case/eq val-expr case-clause ...)
(case/eqv val-expr case-clause ...)

Like case, but using equal?, equal-always?,eq?, or eqv? for comparing the result ofval-expr to the literals in the case-clauses. Thecase/equal form is equivalent to case.