× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Clojure's confusing contains function

Mouna Cheikhna
Nov 20, 2016
<p>It does not check whether a collection contains a value<br>  instead it checks whether an item could be retrieved with get (=&gt; whether a collection contains a key).<br>  Which makes sense for sets (they make no distinction between keys and values),<br>  maps so</p> <pre><code class="language-python">(contains? {:a 1} :a) </code></pre> <p> returns true ,<br>  and for vectors</p> <pre><code class="language-python">(contains? [:foo :bar] 0) is true</code></pre> <p>, because the keys are indices and the vector in question does "contain" the index 0.</p> <p> But nicely in : In Clojure ≥ 1.5 contains? throws when handed an object with no support for "key membership" test.<br>   so instead to check for contains in a list use :<br>     </p> <pre><code class="language-python">(some #{2} '(1 2 5))</code></pre> <p>  which will return 2.<br>   but there's a catch when searching for a falsy value :</p> <pre><code class="language-python">(some #{false} [true false true]) ; = nil</code></pre> <p><br>  so instead we can fix that with</p> <pre><code class="language-python">(some false? [true false true]) ; = true</code></pre> <p><br>  But even better create a function for it:<br>  </p> <pre><code class="language-python">(defn seq-contains? [coll target] (some #(= target %) coll)) (seq-contains? [true false true] false) ; = true</code></pre> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus