Skip to content

Instantly share code, notes, and snippets.

@ichramm
Created August 28, 2020 14:47
Show Gist options
  • Save ichramm/b4476597160f3d45af531641f1dda5af to your computer and use it in GitHub Desktop.
Save ichramm/b4476597160f3d45af531641f1dda5af to your computer and use it in GitHub Desktop.
clojure index of element matching predicate
(defn index-of
[pred coll]
(first (keep-indexed #(when (pred %2) %1) coll)))
; or
(defn indices
[pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(def index-of (comp first indices))
(def last-index-of (comp last indices))
; or
(defn index-of
[pred coll]
(loop [coll coll idx 0]
(when (seq coll)
(if (pred (first coll))
idx
(recur (rest coll) (inc idx))))))
(defn last-index-of
[pred coll]
(loop [coll coll idx 0 e nil]
(if (seq coll)
(recur (rest coll)
(inc idx)
(if (pred (first coll)) idx e))
e)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment