Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure. Drop-every?

Does the Clojure library have a "drop-every" type function? Something that takes a lazy list and returns a list with every nth item dropped?

Can't quite work out how to make this.

cheers

Phil

like image 473
interstar Avatar asked Jan 23 '26 02:01

interstar


1 Answers

(defn drop-every [n xs]
  (lazy-seq
   (if (seq xs)
     (concat (take (dec n) xs)
             (drop-every n (drop n xs))))))

Example:

(drop-every 2 [0 1 2 3 4 5])
;= (0 2 4)

(drop-every 3 [0 1 2 3 4 5 6 7 8])
;= (0 1 3 4 6 7)

As a side note, drop-nth would be a tempting name, as there is already a take-nth in clojure.core. However, take-nth always returns the first item and then every nth item after that, whereas the above version of drop-every drops every nth item beginning with the nth item of the original sequence. (A function dropping the first item and every nth item after the first would be straightforward to write in terms of the above.)

like image 85
Michał Marczyk Avatar answered Jan 27 '26 01:01

Michał Marczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!