liveBook · Manning

Case statement

As explained in Clojure: The Essential Reference

A switch statement is a control-flow construct that selects an execution branch by matching a value against alternative cases.

Clojure’s `case` selects a result by comparing one expression with fixed test constants: `(case expr test then ... default)`. Only the selected `then` form is evaluated. If nothing matches, it returns the optional default; without one, it throws `IllegalArgumentException`. Duplicate test constants also cause an exception. section 3.3.4

Tests are compile-time literals, not expressions evaluated to produce test values. For example, `(inc 0)` in a test position does not become `1`; its list elements act as alternative tests. This also makes quoted symbols surprising: use `alpha` rather than `'alpha` as a symbol test. Compared with `cond` and `condp`, `case` is intended for fast lookup among fixed alternatives. section 3.3.4

(defn error [& args]
  (println "Unrecognized operator for" args))

(defn operator [op] ; #1
  (case op
    ("+" "plus" "sum") +
    ("-" "minus" "subtract") -
    ("*" "x" "times") *
    ("/" "÷" "divide") /
    error))

(defn execute [arg1 op arg2] ; #2
  ((operator op)
         (Integer/valueOf arg1)
         (Integer/valueOf arg2)))

(defn calculator [s] ; #3
  (let [[arg1 op arg2] (clojure.string/split s #"\s+")]
    (execute arg1 op arg2)))

(calculator "10 ÷ 5") ; #4
;; 2

The calculator maps several literal operator names to each function, then uses the selected function to evaluate an input string. section 3.3.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, results, exceptions, and literal-test restrictions, then inspects macro expansion and JVM bytecode.
Examples
Uses a calculator, quoted-symbol pitfalls, keystroke scoring, and a `cond` benchmark.
What it assumes
Assumes familiarity with Clojure forms and conditional expressions.
What you can do after
Apply it in Clojure to dispatch on literal values while avoiding unevaluated-test and duplicate-constant pitfalls.
How it connects
Contrasts with `cond` and `condp` and connects fast dispatch to JVM `tableswitch` bytecode.

Also explained in

Compare how 9 books explain case statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.