【问题标题】:How to drop the nth item in a collection in Clojure?如何在 Clojure 中删除集合中的第 n 个项目?
【发布时间】:2014-07-03 12:18:59
【问题描述】:

如何删除集合中的第 n 个项目?我想做这样的事情:

(def coll [:apple :banana :orange])

(drop-nth 0 coll)  ;=> [:banana :orange]
(drop-nth 1 coll)  ;=> [:apple :orange]
(drop-nth 2 coll)  ;=> [:apple :banana]

有没有比我目前想出的更好的方法?

(defn drop-nth [n coll]
  (concat (take n coll) (nthrest coll (inc n))))

【问题讨论】:

标签: clojure


【解决方案1】:

keep-indexed怎么样?

(defn drop-nth [n coll]
   (keep-indexed #(if (not= %1 n) %2) coll))

这是适用于每个序列的通用解决方案。如果您想坚持使用向量,可以使用subvec,如here 所述。

【讨论】:

  • 这是对我提出的问题的完美回答。更好的是,你和其他人已经向我指出了我应该问的问题,因为无论如何我都在使用向量。 :)
  • 要从列表中删除每个第 n 个元素,只需将条件替换为 (not= (mod %1 n) 0)
【解决方案2】:

这个怎么样

(defn drop-nth [n coll]
  (concat 
    (take n coll)
    (drop (inc n) coll)))

【讨论】:

  • 那行得通,但和我的差不多,对吧?与我最初所做的相比,它有什么好处吗?
  • 几乎相同。我认为 drop 是懒惰的,而 nthrest 不是。
  • 看起来你对 nthrest 不懒惰是正确的,至少如果 Clojure 文档中的 this comment 是准确的。对于nthrest,我实际上无法通过looking at the source 告诉自己。
猜你喜欢
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2020-01-06
相关资源
最近更新 更多