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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With