ClojureDocs

导航

命名空间

take-nth

clojure.core

自 1.0 起可用 ()
  • (take-nth n)
  • (take-nth n coll)
Returns a lazy seq of every nth item in coll.  Returns a stateful
transducer when no collection is provided.
2 Examples
user=> (take-nth 2 (range 10))
(0 2 4 6 8)
;; N <= 0 is a special case
(take 3 (take-nth 0 (range 2)))
;;=> (0 0 0)

(take 3 (take-nth -10 (range 2)))
;;=> (0 0 0)
See Also

Returns a lazy sequence of lists of n items each, at offsets step apart. If step is not supplied, ...

Added by kappa

Returns the value at the index. get returns nil if index out of bounds, nth throws an exception un...

Added by MicahElliott

Return a random element of the (sequential) collection. Will have the same performance characteris...

Added by MicahElliott
3 Notes
    By , created 10.2 years ago

    (take-nth 0 (range 10)) will loop forever.

    By , created 9.9 years ago

    (take-nth 0 coll) will return an infinite sequence repeating for first item from coll. A negative N is treated the same as 0.

    By , created 7.1 years ago, updated 7.1 years ago
    ;; In case you are searching for it, drop-nth is not in core.
    
    (defn drop-nth [n coll]
      (lazy-seq
        (when-let [s (seq coll)]
          (concat (take (dec n) (rest s))
                  (drop-nth n (drop n s))))))
    
    (drop-nth 3 (range 10))
    ;; (1 2 4 5 7 8)
    
    ;; or alternatively: (keep-indexed #(when-not (zero? (rem %1 n)) %2) coll)