Possible Duplicate:
how to return only truthy values as the result of a map operation
I have a collection which has falsy and truthy values. I would like to only count the truthy values, is there a way to do that ?
(count (1 2 3 nil nil)) => 5
If you want to keep the truthy values just need to use the identity
function:
(count (filter identity '(1 2 3 nil nil false true)))
I would recommend doing this with reduce as follows:
(defn count-truthy [coll]
(reduce (fn [cnt val] (if val (inc cnt) cnt)) 0 coll))
Reasons for using reduce in this way:
If you already have a realised sequence, then the following is also a good option, as it will benefit from primitive arithmetic in the loop:
(defn count-truthy [coll]
(loop [s (seq coll) cnt 0]
(if s
(recur (next s) (if (first s) (inc cnt) cnt))
cnt)))
Just remove values that you do not want to count.
(count (remove nil? [1 2 3 nil nil])) => 3
(defn truthy-count [coll]
(reduce + 0
(map #(if % 1 0) coll)))
Although I admit I like dAni's solution better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With