Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first item in a map/list/sequence that satisfies a predicate

Tags:

clojure

I am looking for a function that returns the first element in a sequence for which an fn evaluates to true. For example:

(first-map (fn [x] (= x 1)) '(3 4 1)) 

The above fake function should return 1 (the last element in the list). Is there something like this in Clojure?

like image 849
Matthew Avatar asked Apr 17 '12 13:04

Matthew


1 Answers

user=> (defn find-first          [f coll]          (first (filter f coll))) #'user/find-first user=> (find-first #(= % 1) [3 4 1]) 1 

Edit: A concurrency. :) No. It does not apply f to the whole list. Only to the elements up to the first matching one due to laziness of filter.

like image 149
kotarak Avatar answered Oct 03 '22 16:10

kotarak