Search code examples
clojure

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


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?


Solution

  • 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.