user4813927
user4813927

Reputation:

Case cases in Clojure

Besides the constant time dispatch of case, what could be other points leading me to use case instead of cond condp?

Upvotes: 3

Views: 1288

Answers (2)

Thumbnail
Thumbnail

Reputation: 13483

Even where it's slower, case is often more expressive than if:

(defn fact [n]
  (case n
    0 1
    (* n (fact (dec n)))))

... reads better than

(defn fact [n]
  (if (zero? n) 1
    (* n (fact (dec n)))))

This is a matter of taste, but the case phrase is one form shorter.

Upvotes: 3

Sam Estep
Sam Estep

Reputation: 13324

  1. Assuming that you really are dealing with compile-time constants, case semantically conveys the nature of your condition better than cond or condp.
  2. case is more concise than cond or condp.

Example:

(cond
  (= foo 1) :one
  (= foo 2) :two
  (= foo 3) :three)

(condp = foo
  1 :one
  2 :two
  3 :three)

(case foo
  1 :one
  2 :two
  3 :three)

I can't comment on any performance aspects, but as always, that should be the least of your considerations.

Upvotes: 7

Related Questions