clojure.core/keep¶
Returns a lazy sequence of the non-nil results of (f item). Note, this means false return values will be included. f must be free of side-effects. Returns a transducer when no collection is provided.
Examples¶
Note by miner¶
Note the difference between filter and keep. filter returns the original items in a collection that satisfy the predicate. keep returns the non-nil results of the given function.
Note by Dimagog¶
keep is like a map that filters out nil values produced by f and could be defined as:
(def my-keep (comp (partial remove nil?) map))
or, perhaps more traditionally:
(defn my-keep [& args] (remove nil? (apply map args)))
Note by bfontaine¶
Note that, unlike map, keep doesn’t accept multiple collections:
(filter identity (map get [{:a 1} {:b 2} {:d 3}] [:a :b :c]))
; => (1 2)
(keep get [{:a 1} {:b 2} {:d 3}] [:a :b :c])
; => ArityException Wrong number of args (3) passed to: core/keep
Note by MicahElliott¶
It's useful to consider filter and remove as a pair of complementary/similar functions that both return the original items, whereas keep is rather specialized/different.
See also¶
- clojure.core/keep-indexed (5)
- clojure.core/map (13)
- clojure.core/filter (6)
- clojure.core/remove (6)
Content from the matching ClojureDocs page, with authors credited on each contribution.