测试列表是否包含Clojure中的特定值 [英] Test whether a list contains a specific value in Clojure

查看:143
本文介绍了测试列表是否包含Clojure中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



特别是,的行为包含?

什么是测试列表是否包含Clojure中的给定值的最佳方法? / code>目前令我感到困惑:

 (包含?'(100 101 102)101)=> false 

我可以明白地编写一个简单的函数来遍历列表并测试平等,但肯定会做一个标准的方法?

解决方案

啊,包含? ...据说是五大常见问题之一:Clojure。



它不检查集合是否包含值;它检查是否可以使用 get 检索项目,或者换句话说,是否收集包含密钥。这对于集合(可以认为不区分键和值),地图(so (包含?{:foo 1}:foo) true )和向量(但请注意(包含?[:foo:bar] 0) true ,因为这里的键是索引,并且所涉及的向量包含索引 0 !)。



为了增加混淆,在调用 contains?没有意义的情况下,它只返回 false ;这是在(包含?:foo 1) 以及 (包含?'(100 101 102)101 ) 更新:在Clojure中,≥1.5 包含?抛出一个类型的对象不支持预期的关键会员测试。



正确的做法如下:

 ;大部分时间这个工程
(一些#{101}'(100 101 102))

当搜索一堆物品之一时,可以使用较大的套件;在搜索 false / nil 时,可以使用 false? / nil? - 因为(#{x} x)返回 x ,因此(#{nil} nil) nil ;当搜索多个项目中的一个可能是 false nil 时,可以使用

 (some(zipmap [... items ...](repeat true))the-collection)

(请注意,这些项目可以传递给任何类型的集合中的 zipmap 。 )


What is the best way to test whether a list contains a given value in Clojure?

In particular, the behaviour of contains? is currently confusing me:

(contains? '(100 101 102) 101) => false

I could obviously write a simple function to traverse the list and test for equality, but there must surely be a standard way to do this?

解决方案

Ah, contains?... supposedly one of the top five FAQs re: Clojure.

It does not check whether a collection contains a value; it checks whether an item could be retrieved with get or, in other words, whether a collection contains a key. This makes sense for sets (which can be thought of as making no distinction between keys and values), maps (so (contains? {:foo 1} :foo) is true) and vectors (but note that (contains? [:foo :bar] 0) is true, because the keys here are indices and the vector in question does "contain" the index 0!).

To add to the confusion, in cases where it doesn't make sense to call contains?, it simply return false; this is what happens in (contains? :foo 1) and also (contains? '(100 101 102) 101). Update: In Clojure ≥ 1.5 contains? throws when handed an object of a type that doesn't support the intended "key membership" test.

The correct way to do what you're trying to do is as follows:

; most of the time this works
(some #{101} '(100 101 102))

When searching for one of a bunch of items, you can use a larger set; when searching for false / nil, you can use false? / nil? -- because (#{x} x) returns x, thus (#{nil} nil) is nil; when searching for one of multiple items some of which may be false or nil, you can use

(some (zipmap [...the items...] (repeat true)) the-collection)

(Note that the items can be passed to zipmap in any type of collection.)

这篇关于测试列表是否包含Clojure中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆