如何从Clojure中的序列中删除项目? [英] How can I remove an item from a sequence in Clojure?

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

问题描述

首先,我假设每个结构特定的序列将有不同的方式来移除项目:向量可以通过索引,列表可以首先删除或最后, < / p>

其次,我假设有一些结构不可知的移除方法;他们在 seq 接口上工作。



由于序列在Clojure中是不可变的,所以我怀疑你在做什么是做一个便宜的原来,只有没有原始项目。这意味着列表解析可以用于删除,但我怀疑这将是不必要的冗长。



请给出一些惯用的例子,从Clojure序列中删除项目的不同方式。

解决方案

没有单一的界面可以从Clojure的所有数据结构类型中删除事物,可能是因为不同的性能特征。 / p>

 (disj#{:foo:bar}:foo); => #{:bar} 
(dissoc {:foo 1:bar 2}:foo); => {:bar 2}
(pop [:bar:foo]); => [:bar]
(pop(list:foo:bar)); => (:bar)

这些也可以工作(返回 seq ):

 (remove#{:foo}#{:foo:bar}); => (:bar)
(remove#{:foo} [:foo:bar]); => (:bar)
(remove#{:foo}(list:foo:bar)); => (:bar)

这不适用于哈希映射,因为当您遍历地图时,你得到键/值对。但这个工作原理:

 (remove(fn [[kv]](#{:foo} k)){:foo 1 :bar 2}); => ([:bar 2])


First, I assume each structure-specific sequences would have different ways to remove an item: Vectors could be by index, List could be remove first or last, Set should be passing of the actual item to remove, etc.

Second, I assume there are some methods for removal that are structure agnostic; they work on seq interface.

Since sequences are immutable in Clojure, I suspect what you're actually doing is making a cheap copy of the original, only without the original item. This means list comprehension could be used for removal, but I suspect it would be unnecessarily verbose.

Please give some idiomatic examples of the different ways to remove items from Clojure sequences.

解决方案

There is no single interface for removing things from all of Clojure's data structure types, possibly because of the different performance characteristics.

(disj #{:foo :bar} :foo)       ; => #{:bar}
(dissoc {:foo 1 :bar 2} :foo)  ; => {:bar 2}
(pop [:bar :foo])              ; => [:bar]
(pop (list :foo :bar))         ; => (:bar)

These also work (returning a seq):

(remove #{:foo} #{:foo :bar})      ; => (:bar)
(remove #{:foo} [:foo :bar])       ; => (:bar)
(remove #{:foo} (list :foo :bar))  ; => (:bar)

This doesn't work for hash-maps because when you iterate over a map, you get key/value pairs. But this works:

(remove (fn [[k v]] (#{:foo} k)) {:foo 1 :bar 2})  ; => ([:bar 2])

这篇关于如何从Clojure中的序列中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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