Pure Danger Tech


Learning Clojure #15: case

30 May 2010

Way back in Learning Clojure #12 I talked about using condp as a simpler form of cond, kind of like a Java switch. In Clojure 1.2, there is a new function called case that is even a closer match for this idea.

In the example from the last post:

(defn test-condp [x]
(condp = x
    0 "got 0"
    1 "got 1"
    (str "else " x)))

you can rewrite this example with case as follows:

(defn test-case [x] 
         (case x 
           0 "got 0"
           1 "got 1"
           (str "else " x)))

There are several restrictions in case vs condp:

  • case only works with “=” as the condition function
  • the matching expressions must be compile-time literals (strings, numbers, symbols, keywords, and collections of those

The benefit of case is that unlike cond and condp, it is not a sequential search for a match – the match is O(1). From an implementation point of view, all of the match expressions become keys in a map and the match occurs via a lookup on that map.