cond をスリムにする condp

普通の cond

(defn cond1 [x]
  (cond
    (= x :hey) "Hey!"
    (= x :bye) "Bye!"
    (= x :hi) "Hi!"))

重複するパターンがあります。condp を使うとスマートに。

(defn condp1 [x]
  (cond = x
     :hey "Hey!"
     :bye "Bye!"
     :hi "Hi!"))

次の例はちょっとトリッキーなので、あまり推奨されないかもしれない。

(defn cond2 [x]
  (cond
    (list? x) "List!"
    (map? x) "Map!"
    (vector? x) "Vector!"))
(defn condp2 [x]
  (condp #(%1 %2) x
    list? "List!"
    map? "Map!"
    vector? "Vector!"))


参考 Learning Clojure #12: condp