How to remove the nth item in a collection in Clojure?

How can I remove the nth item in a collection? I want to do something like this:

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

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

Is there a better way to do this than what I have come up with so far?

(defn drop-nth [n coll]
  (concat (take n coll) (nthrest coll (inc n))))
+4
source share
2 answers

How about using keep-indexed?

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

This is a general solution that works with every sequence. If you want to stick with vectors, you can use subvecas described here .

+11
source

How about this

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

Source: https://habr.com/ru/post/1547000/


All Articles