19
votes

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

2

2 Answers

35
votes

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.

8
votes

Use filter and first

user=> (->> (range) (filter #(> % 10)) first)
11
user=> (first (filter #(> % 10) (range)))
11