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

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

问题描述

在Clojure中测试列表是否包含给定值的最好方法是什么?



特别是,contains的行为?目前令我混淆:

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

我可以写一个简单的函数来遍历列表并测试相等性,

...应该是前五个常见问题之一:Clojure。



它不会检查集合是否包含值;它检查是否可以使用 get 检索项目,或换句话说,集合是否包含键。这对于集合(可以被认为不区分键和值),映射(因此(包含?{:foo 1}:foo) true )和向量(但注意(包含?[:foo:bar] 0) > true ,因为这里的键是索引,并且所讨论的向量包含索引 0 !)。



要添加混乱,在调用包含?没有意义的情况下,它只是返回 false ;这是在(包含?:foo 1) 以及 (包含?'(100 101 102)101 ) 在Clojure中,<1.5> 包含?不支持预期的关键成员资格测试。



正确的方法如下:

 ;大多数时间这个工作
(一些#{101}'(100 101 102))

当搜索一堆项目之一时,可以使用更大的集合;当搜索 false / nil 时,可以使用 false? / nil? - 因为(#{x} x)返回 code>,因此(#{nil} nil) nil 当搜索其中一些可能是 false nil 的一个项目时,可以使用

 (一些(zipmap [... the items ...](重复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天全站免登陆