I would recommend doing this with a decrease as follows:
(defn count-truthy [coll] (reduce (fn [cnt val] (if val (inc cnt) cnt)) 0 coll))
Reasons to use abbreviations in this way:
- Most likely, it will be more efficient and benefit from Clojure's new reducer features that allow facts to decline in many collections.
- It avoids creating an intermediate sequence (what would happen if you used a lazy sequence function like a filter).
If you already have an implemented sequence, then this is also a good option, since it will benefit from primitive arithmetic in a loop:
(defn count-truthy [coll] (loop [s (seq coll) cnt 0] (if s (recur (next s) (if (first s) (inc cnt) cnt)) cnt)))
mikera
source share