I wanted to write a function in clojure to return the nth non nil value in a collection. Like the inexperienced clojure student that I am, I wrote something like this
(defn nth-not-nil [n coll] (loop [m 0 x (first coll) r (rest coll)] (if (nil? x) nil (if (= m n) x (recur (inc m) (first r) (rest r))))))
First of all, that doesn't work, second of all, it just smells like re-inventing the wheel. Here is a much better way using built in functions:
(nth (filter #(not (nil? %)) coll) n)
It's even a one-liner that, when read out loud, sounds like what I was looking for.
But wait, I want to return nil if the nth not nil value is not found! That's fine, nth allows you to specify a not-found value:
clojure.core/nth ([coll index] [coll index not-found]) Returns the value at the index. get returns nil if index out of bounds, nth throws an exception unless not-found is supplied. nth also works for strings, Java arrays, regex Matchers and Lists, and, in O(n) time, for sequences.
(nth (filter #(not (nil? %)) coll) n nil)