Search code examples
clojure

Find index of an element matching a predicate in Clojure?


With Clojure, how do I find the first index with a positive value in this vector [-1 0 3 7 9]?

I know you can get the first result of something rather elegantly with first and filter:

(first (filter pos? [-1 0 99 100 101]))

This code returns the value 99. The answer I want is the index which is 2.


Solution

  • Using keep-indexed you can get a sequence of indices for which a predicate is satisfied:

    (defn indices [pred coll]
       (keep-indexed #(when (pred %2) %1) coll))
    

    With this simple function you'll solve your problem with the expression

    user=> (first (indices pos? [-1 0 99 100 101]))
    2
    

    Note that, due to the lazyness of keep-indexed (and indices), the entire sequence need not be realized so no extraneous calculations are performed.