Issue with Clojure 'contains'

耗尽温柔 提交于 2019-12-04 02:57:34

问题


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.


回答1:


A vector is similar to an array. contains? returns true if the key exists in the collection. You should be looking for the "key/index" 0, 1 or 2

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

If you were using a hash...

user=> (def stooges {:moe "Moe" :larry "Larry" :curly "Curly"})
#'user/stooges
user=> (contains? stooges :moe)
true
user=> (contains? stooges :foo)
false

As mikera suggests, you probably want something like clojure.core/some




回答2:


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



回答3:


contains? support Set, if you use clojure-1.4

user=> (contains? #{:a, :b} :a)
true

user=> (contains? (set stooges) "Moe")
true


来源:https://stackoverflow.com/questions/11963193/issue-with-clojure-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!