문제

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

도움이 되었습니까?

해결책

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

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top