Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select first item of a collection that satisfies given predicate in clojure

Tags:

clojure

Is there a function in clojure that (given a predicate and a collection), selects the first item that satisfies the given predicate and stop the iteration?

for example:

(select-first #(> % 10) (range))
=> 11

If not, maybe someone could hint me about an idiomatic implementation

like image 875
szymanowski Avatar asked Dec 04 '13 15:12

szymanowski


1 Answers

There are multiple possibilities.

some

some returns the first non-nil value its predicate returns.

(some #(when (> % 10) %) (range)) ;; => 11

filter + first

filter retains those elements that match a predicate, first retrieves the first of them.

(first (filter #(> % 10) (range))) ;; => 11

remove + first

If you want to find the first element that does not match your predicate, remove is your friend:

(first (remove #(<= % 10) (range))) ;; => 11

Or with some:

(some #(when-not (<= % 10) %) (range)) ;; => 11

So, that's it, I guess.

like image 187
xsc Avatar answered Oct 26 '22 00:10

xsc