clojure

Alternative function to "some" in Clojure that returns true or false


I want to check whether any element in a list satisfies given condition. I have tried using some, which returns either true or nil, but can't seem to find a function with similar functionality that would retrieve true/false.

Example - checking whether there is a 6 in a list:

(some #(= 6 %) numbers-list))


Solution

  • This is I think the most idiomatic approach (using set as function), but this does return nil or the value itself:

    (some #{6} [1 2 3 4 5 6 7])
    ;; => 6
    

    As mentioned in a comment on your question, this can be converted to boolean using boolean.

    Other approach that returns boolean is by converting to a set and using contains? you return a boolean:

    (contains? (set [1 2 3 4 5 6 7]) 6)
    ;; => true
    

    (since contains? "for numerically indexed collections like vectors and Java arrays, ... tests if the numeric key is within the range of indexes.") Does need extra conversion.

    Or similarly using Java interop (but working on vector and list as well):

    (.contains [1 2 3 4 5 6 7] 6)
    ;; => true
    

    Also see Test whether a list contains a specific value in Clojure.