1.3.0 permalink 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)
    
    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:1377 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"
   :static true}
  [coll key] (. clojure.lang.RT (contains coll key)))
Vars in clojure.core/contains?:
Used in 0 other vars

Comments top

1 comment(s) for contains?.

As Rich points out on the ML:

contains? tells you whether or not get will succeed. It is not a "rummager".

contains? and get abstract over fast lookup.

Log in to add a comment.