keep-indexed

clojure.core

  • (keep-indexed f coll)
Returns a lazy sequence of the non-nil results of (f index item). Note,
this means false return values will be included. f must be free of
side-effects.

3 Examples top

  • user=> (keep-indexed #(if (odd? %1) %2) [:a :b :c :d :e])
    (:b :d)
  • user=> (keep-indexed #(if (pos? %2) %1) [-9 0 29 -7 45 3 -8])
    (2 4 5)
    ;; f takes 2 args: 'index' and 'value' where index is 0-based
    ;; when f returns nil the index is not included in final result
    user=> (keep-indexed (fn [idx v]
                           (if (pos? v) idx)) [-9 0 29 -7 45 3 -8])
    (2 4 5)
  • (defn position [x coll & {:keys [from-end all] :or {from-end false all false}}]
      (let [all-idxs (keep-indexed (fn [idx val] (when (= val x) idx)) coll)]
      (cond
       (true? from-end) (last all-idxs)
       (true? all)      all-idxs
       :else            (first all-idxs))))
    
    user> (position [1 1] [[1 0][1 1][2 3][1 1]])
    1
    user> (position [1 1] [[1 0][1 1][2 3][1 1]] :from-end true)
    3
    user> (position [1 1] [[1 0][1 1][2 3][1 1]] :all true)
    (1 3)
    
    user> (def foo (shuffle (range 10)))
    #'user/foo
    user> foo
    (5 8 9 1 2 7 0 6 3 4)
    user> (position 5 foo)
    0
    user> (position 0 foo)
    6
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:6356 top

(defn keep-indexed
  "Returns a lazy sequence of the non-nil results of (f index item). Note,
  this means false return values will be included.  f must be free of
  side-effects."
  {:added "1.2"
   :static true}
  ([f coll]
     (letfn [(keepi [idx coll]
               (lazy-seq
                (when-let [s (seq coll)]
                  (if (chunked-seq? s)
                    (let [c (chunk-first s)
                          size (count c)
                          b (chunk-buffer size)]
                      (dotimes [i size]
                        (let [x (f (+ idx i) (.nth c i))]
                          (when-not (nil? x)
                            (chunk-append b x))))
                      (chunk-cons (chunk b) (keepi (+ idx size) (chunk-rest s))))
                    (let [x (f idx (first s))]
                      (if (nil? x)
                        (keepi (inc idx) (rest s))
                        (cons x (keepi (inc idx) (rest s)))))))))]
       (keepi 0 coll))))
Vars in clojure.core/keep-indexed:
Used in 0 other vars

Comments top

No comments for keep-indexed. Log in to add a comment.