Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

How can I drop 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 of doing this than what I've come up with so far?

(defn drop-nth [n coll]
  (concat (take n coll) (nthrest coll (inc n))))
like image 832
Josh Glover Avatar asked Jul 03 '14 12:07

Josh Glover


2 Answers

How about using keep-indexed?

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

This is a generic solution that works with every sequence. If you want to stick with vectors, you could use subvec as described here.

like image 123
sloth Avatar answered Dec 04 '22 21:12

sloth


How about this

(defn drop-nth [n coll]
  (concat 
    (take n coll)
    (drop (inc n) coll)))
like image 31
KobbyPemson Avatar answered Dec 04 '22 20:12

KobbyPemson