Pergunta

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

Foi útil?

Solução

(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.)

Outras dicas

If the input list length is a multiple of n you can use the partition function:

(defn drop-every [n lst] (apply concat (map butlast (partition n lst))))
(take 5 (drop-every 3 (range)))
; (0 1 3 4 6)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top