Search code examples
clojure

why Clojure conatins? behave so strangely?


Why clojure output true fo first one and false for the second one

(def myset [3 5 7 11 13 17 19])
(defn check-n
[n]
(contains? myset n))

(check-n 1)
(check-n 20)

Solution

  • contains? is function for checking keys in collection. It can be used with map:

    (contains? {:a 1 :b 2} :a)
    => true
    (contains? {:a 1 :b 2} :c)
    => false
    

    or with vector- in this case, it checks whether vector contains given index:

    (contains? [1 2 3] 0)
    => true
    (contains? [1 2 3] 3)
    => false
    

    If you want to check occurence of number, use .contains from Java:

    (.contains [1 2 3] 3)
    => true
    

    or some with set used as predicate:

    (some #{3} [1 2 3])
    => 3
    (some #{4} [1 2 3])
    => nil