Spoon of Code

Spoon of code is a small blog post (a gist, a code kata) solving a simple (possibly common) problem. Straight to the point. Mostly in Clojure as this is the main language I use these days. Like this:

Find the index of an item in a collection by given predicate


You have a list of items [{:a 1} {:a 3} {:a 2} {:a 5}] and you want to know the index of the first item for which value of :a is even


(defn pred->index 
  [pred coll] 
  (first (keep-indexed #(when (pred %2) %1) coll))) 
(def data [{:a 1} {:a 3} {:a 2} {:a 5}]) 
(pred->index (comp even:a) data) 
; 2


pred->index uses keep-indexed to return only the non-nil results of calling provided pred (in above case that’s (comp even? :a)) on all items in coll. The function then returns the first result from that lazy sequence.

And that’s it - come back soon for more Spoons of Code (and other things)!