You're viewing version 1.2.0 of contains?. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

contains?

clojure.core

  • (contains? coll key)
Returns true if key is present in the given collection, otherwise
returns false. Note that for numerically indexed collections like
vectors and Java arrays, this tests if the numeric key is within the
range of indexes. 'contains?' operates constant or logarithmic time;
it will not perform a linear search for a value. See also 'some'.

2 Examples top

  • ;; `contains?` is straightforward for maps:
    user=> (contains? {:a 1} :a)
    true
    user=> (contains? {:a nil} :a)
    true
    user=> (contains? {:a 1} :b)
    false
    
    
    ;; It's likely to surprise you for other sequences because it's 
    ;; about *indices*, not *contents*:
    
    user=> (contains? [:a :b :c] :b)
    false
    
    user=> (contains? [:a :b :c] 2)
    true
    
    user=> (contains? "f" 0)
    true
    
    user=> (contains? "f" 1)
    false
    
    
    ;; It can be applied to non-sequences:
    
    user=> (contains? 5 3)
    false
    
    
    ;; Although lists are sequences, `contains?` seems to always return
    ;; `false` for them. (Clojure 1.1)
    ;;
    ;; Note, this no longer works in Clojure 1.5, throwing an 
    ;; IllegalArgumentException.
    
    user=> (contains? '(1 2 3) 1) => false
    
    
  • ;; Can be used to test set membership
    user=> (def s #{"a" "b" "c"})
    
    user=> (contains? s "a")
    true
    
    user=> (contains? s "z")
    false
Log in to add / edit an example.

See Also top

  • 0
    clojure.core/some

    Returns the first logical true value of (pred x) for any x in coll,

  • 0
    clojure.core/get

    Returns the value mapped to key, not-found or nil if key not present.

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:1145 top

(defn contains?
  "Returns true if key is present in the given collection, otherwise
  returns false.  Note that for numerically indexed collections like
  vectors and Java arrays, this tests if the numeric key is within the
  range of indexes. 'contains?' operates constant or logarithmic time;
  it will not perform a linear search for a value.  See also 'some'."
  {:added "1.0"}
  [coll key] (. clojure.lang.RT (contains coll key)))
Vars in clojure.core/contains?: defn key

Comments top

2 comment(s) for contains?.

If like me you wanted to find a value in a collection and read this article then you'll need to find an alternative. So instead of:

(contains (1 2 3) 1)

I used:

(some #(= 1 %) (1 2 3))

Hope that helps.

For collections I use the java.util.Collection#contains() method:

user=> (.contains [1 2 3] 1)
true
user=> (.contains [1 2 3] 4)
false
Log in to add a comment.