Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Clojure 'contains'

I am going through some Clojure tutorials using Closure Box, and entered the following code:

user> (def stooges (vector "Moe" "Larry" "Curly"))
#'user/stooges
user> (contains? stooges "Moe")
false

Shouldn't this evaluate to TRUE ? Any help is appreciated.

like image 379
user1017102 Avatar asked Aug 15 '12 02:08

user1017102


1 Answers

This is a common trap! I remember falling into this one when I was getting started with Clojure :-)

contains? checks whether the index (0, 1, 2, etc.) exists in the collection.

You probably want something like:

(some #{"Moe"} stooges)
=> "Moe"    <counts as boolean true>

(some #{"Fred"} stooges)
=> nil      <counts as boolean false>

Or you can define your own version, something like:

(defn contains-value? [element coll]
  (boolean (some #(= element %) coll)))

(contains-value? "Moe" stooges)
=> true
like image 150
mikera Avatar answered Dec 20 '22 13:12

mikera