Counting Only True Values ​​in a Collection

Possible duplicate:
how to return only true values ​​as a result of a card operation

I have a collection that has false and true values. I would only like to consider true values, is there any way to do this?

(count (1 2 3 nil nil)) => 5

+7
source share
5 answers

If you want to keep true values, you just need to use the identity function:

  (count (filter identity '(1 2 3 nil nil false true))) 
+19
source

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))) 
+6
source

Just delete the values ​​you do not want to read.

 (count (remove nil? [1 2 3 nil nil])) => 3 
+3
source
 (defn truthy-count [coll] (reduce + 0 (map #(if % 1 0) coll))) 

Although I admit, it is better to use a dAni solution.

+2
source

genral pattern filters the sequence and counts the results

 (count (filter #(if % %) [1 2 3 nil nil false])) 3 

#(if % %) is just a short truth test that returns an element only if it is true or something false (nil) otherwise

+2
source

All Articles