在Clojure中从另一组中删除一组 [英] Remove one set from another in Clojure

查看:87
本文介绍了在Clojure中从另一组中删除一组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(def mine '(a b c))
(def yours '(a b))
(remove yours mine)
 ; should return (c)

我被建议在另一个线程中使用remove,但是它不起作用。
任何人都可以建议吗?

I was advised to use remove in another thread but it doesn't work. Anyone can advise?

推荐答案

假设您要从 mine 您的$code>中也存在的每个元素,都有几种方法。您可以将列表转换为集合,并使用差异,例如:

Assuming you want to remove from mine every element that also exists in yours, there are a few approaches. You can convert the lists to sets and use difference, like this:

(require '[clojure.set :refer [difference]])

(def mine '(a b c))
(def yours '(a b))

(difference (set mine) (set yours))
;; => #{c}

但这不会保留我的剩余元素的顺序。如果要保留订单,则可以使用删除。为此,我们首先定义一个 yours?谓词,如果该元素出现在 yours 中,则该谓词将对元素返回true。 :

But this does not preserve the order of elements that remain from mine. If you want to preserve the order, you can instead use remove. To do that, we first define a yours? predicate that will return true for an element iff that element occurs in yours:

(def yours-set (set yours))
(def yours? (partial contains? yours-set))

如果我们的集合您的人仅包含 truthy 像这样的值既不是 nil 也不是 false ,我们可以将其定义为(由您自己定义吗? (设置您的)),因为集合实现了 IFn 界面,但是如果您的包含诸如 nil false @amalloy指出。

If our set yours only contains truthy values like that are neither nil nor false, we could define it like (def yours? (set yours)) since a set implements the IFn interface but this approach will not work if yours contains elements such as nil or false as @amalloy pointed out.

(remove yours? mine)
;; => (c)

上面的代码意味着我们从 mine 您的是您的?评估为true。另一种更详细的方法是使用remove的相反方法,即 filter ,然后

The above code means that we remove every element from mine for which yours? evaluates to true. Yet another, more verbose approach, is to use the opposite of remove, that is filter, and passing in the opposite of the predicate.

(filter (complement yours?) mine)
;; => (c)

但我认为这里没有更详细的方法。

but I see no gain of that more verbose approach here.

如果您知道要作为向量,则可以改为使用插入,在删除换能器中作为参数。

If you know that you want a vector as a result, you can instead use into, passing in a removeing transducer as argument.

(into [] (remove yours?) mine)
;; => [c]

这篇关于在Clojure中从另一组中删除一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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