Clojure:惯用的方式调用包含?在惰性序列上 [英] Clojure: Idiomatic way to call contains? on a lazy sequence

查看:153
本文介绍了Clojure:惯用的方式调用包含?在惰性序列上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个惯用的方法来确定LazySeq是否包含元素?从Clojure 1.5调用包含?抛出IllegalArgumentException:

  IllegalArgumentException ?不支持类型:clojure.lang.LazySeq 
clojure.lang.RT.contains(RT.java:724)

在1.5之前,据我所知,它总是返回false。



我知道在LazySeq上调用包含?可能永远不会返回,因为它可以是无限的。



我想到的是:


如果我知道这是不是,

 (defn lazy-contains?[col key] 
(not(empty?(filter#(= key%)col))) $ b

但它感觉不太对。有没有更好的方法?

解决方案

首先,延迟seqs不是有效的检查成员资格。考虑使用set而不是惰性seq。



如果一个集合不切实际,你的解决方案不坏。几个可能的改进:


  1. 不空有点尴尬。只要使用seq就足以得到一个nil-or-truthy值,用户可以在if中使用。如果你想要true或false,你可以用布尔值换行。



  2. 因为你只关心第一个匹配,所以你可以使用一些代替过滤器和seq。使用一个字符集,如#{key},虽然如果key是nil,这将总是返回nil是否找到我们的nil。


一起给你:

 (defn lazy-包含?[col key] 
一些#{key} col))


Is there an idiomatic way of determining if a LazySeq contains an element? As of Clojure 1.5 calling contains? throws an IllegalArgumentException:

IllegalArgumentException contains? not supported on type: clojure.lang.LazySeq      
clojure.lang.RT.contains (RT.java:724)

Before 1.5, as far as I know, it always returned false.

I know that calling contains? on a LazySeq may never return as it can be infinite. But what if I know it isn't and don't care if it is evaluated eagerly?

What I came up with is:

(defn lazy-contains? [col key]
  (not (empty? (filter #(= key %) col))))

But it doesn't feel quite right. Is there a better way?

解决方案

First, lazy seqs are not efficient for checking membership. Consider using a set instead of a lazy seq.

If a set is impractical, your solution isn't bad. A couple of possible improvements:

  1. "Not empty" is a bit awkward. Just using seq is enough to get a nil-or-truthy value that your users can use in an if.You can wrap that in boolean if you want true or false.

  2. Since you only care about the first match, you can use some instead of filter and seq.

  3. A convenient way to write an equality predicate is with a literal set, like #{key}, though if key is nil this will always return nil whether nil is found our not.

All together that gives you:

(defn lazy-contains? [col key]
  (some #{key} col))

这篇关于Clojure:惯用的方式调用包含?在惰性序列上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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