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

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

问题描述

首先,我假设每个特定于结构的序列都有不同的删除项目的方法:向量可以通过索引,列表可以首先或最后删除,Set 应该是传递要删除的实际项目,等等.

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.

其次,我假设有一些与结构无关的移除方法;他们在seq接口上工作.

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

由于 Clojure 中的序列是不可变的,我怀疑您实际上在做的是制作原始项目的廉价副本,只是没有原始项目.这意味着列表理解可用于删除,但我怀疑它会不必要地冗长.

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.

请给出一些从 Clojure 序列中删除项目的不同方法的惯用示例.

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

推荐答案

没有单一的接口可以从 Clojure 的所有数据结构类型中删除内容,可能是因为性能特征不同.

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)

这些也有效(返回一个 seq):

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天全站免登陆