Last Updated: September 30, 2021
·
16.27K
· jackattack

Checking for the presence of an element in a vector in Clojure

To determine whether a vector contains an element, use the some function (not contains?).

some will return the first element for which the predicate function returns true, and nil otherwise. contains? checks if a key is contained in the collection. In vectors, the keys are the indexes of the elements, so it checks whether an element exists at that index.

; some returns the first element that returns true from the function
(some #(= 3 %) [1 2 3 4 5]) ; => 3
(some #(= :nope %) [1 2 3 4 5]) ; => nil

; contains returns true if an element exists at that index in the vector
(contains? [1 1 1 1 1] 3) ; => true
(contains? [5 5 5 5] 5) ; => false
(contains? [nil nil nil] 1) ;=> true