2

Like the title says, I'm looking for a function in Clojure that returns me the index of the first element in a map to satisfy a condition, I know how to do it, but if something is already available in the API I would like to us it.

Example:

(strange-fn #(even? %) '(1 3 5 7 9 4)) 
=> 5
didierc
  • 14,572
  • 3
  • 32
  • 52
Kenny D.
  • 927
  • 3
  • 11
  • 29
  • 3
    As an aside, `#(even? %)` is just `even?`. – amalloy Nov 10 '12 at 04:14
  • A similar question has been asked here: See http://stackoverflow.com/questions/4830900/how-do-i-find-the-index-of-an-item-in-a-vector for other answers and discussions. – 0dB Nov 11 '12 at 12:59

2 Answers2

5

You provided a list rather than a map in your example, so I assume you mean any sequence.

One simple way to do it is to just count the number of items returned from take-while:

(defn strange-fn [f coll]
  (count (take-while (complement f) coll)))

(strange-fn #(even? %) '(1 3 5 7 9 4))
;=> 5
JohnJ
  • 4,753
  • 2
  • 28
  • 40
5

It's easy enough to do, but beware that most of the time if you're writing code that works with indices of things (especially lazy-seqs), it's usually possible to do the whole thing much more tidily by just working with sequences. However, if you're certain you want to deal in indices, it's as simple as (fn [pred coll] (first (keep-indexed (fn [i x] (when (pred x) i)) coll))).

amalloy
  • 89,153
  • 8
  • 140
  • 205