Why Not a Function #25: list-index-of
(defn list-index-of [list element] (let [r (reduce (fn [n x] (if (= x element) (reduced n) (inc n))) 0 list)] (when (not= r (count list)) r)))
Checking an index of an element in a list cannot be done using a dedicated function in Clojure. If possible, it may be better to use a vector and its
.indexOf method in this case. It still must do a linear search, mind you.
We can use
list-index-of. If element is not found it will return
nil otherwise it will return a zero-based index.
(list-index-of '(:green :amber :red) :blue) => nil (list-index-of '(:green :amber :red) :amber) => 1