Skip to content

clojure.core/keep

View this page on ClojureDocs

Type: function Added: Clojure 1.2 Examples: 8 Runnable: 8
([f] [f coll])

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

by dpritchett on
by yasuto on
by yasuto on
by miner on
by num1 on
by dkinzer on
by huahaiy on
by blue0513 on

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


Content from the matching ClojureDocs page, with authors credited on each contribution.