Created
August 28, 2020 14:47
-
-
Save ichramm/b4476597160f3d45af531641f1dda5af to your computer and use it in GitHub Desktop.
clojure index of element matching predicate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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