可能重复:
如何仅返回真实值作为映射操作的结果
我有一个包含虚假和真实值的集合。我只想计算真实值,有没有办法做到这一点?
(计数 (1 2 3 nil nil)) => 5
如果你想保持真实值只需要使用identity
函数:
(count (filter identity '(1 2 3 nil nil false true)))
我建议使用 reduce 执行此操作,如下所示:
(defn count-truthy [coll]
(reduce (fn [cnt val] (if val (inc cnt) cnt)) 0 coll))
以这种方式使用reduce的原因:
如果您已经有一个已实现的序列,那么以下也是一个不错的选择,因为它将受益于循环中的原始算术:
(defn count-truthy [coll]
(loop [s (seq coll) cnt 0]
(if s
(recur (next s) (if (first s) (inc cnt) cnt))
cnt)))
只需删除您不想计算的值。
(count (remove nil? [1 2 3 nil nil])) => 3
(defn truthy-count [coll]
(reduce + 0
(map #(if % 1 0) coll)))
虽然我承认我更喜欢 dAni 的解决方案。
一般模式是过滤序列并计算结果
(count (filter #(if % %) [1 2 3 nil nil false]))
3
这#(if % %)
只是对真实性的简短测试,仅当项目为真实或虚假(nil)时才返回项目