take-nth selects every nth element from a sequential collection, beginning with its first element. With n = 3, it keeps positions 0, 3, 6, and so on. The two-argument form returns a lazy sequence; the one-argument form returns a stateful transducer. section 10.9 section 7.2
For a positive integer n, take-nth follows this contract:
- Include the first element, drop n - 1 elements, then repeat until the input ends. section 10.9
- Accept any sequential collection; omit coll when creating a transducer for use with sequence, into, or transduce. section 10.9 section 7.2
- Treat sequential decimal n values by rounding up; the transducer form instead doubles the decimal value, so corner-case behavior differs. section 10.9
- Handle nil, zero, and negative n cautiously: the sequential form returns an empty sequence for nil and repeats its first item for nonpositive values, while the transducer can throw exceptions. section 10.9
Selecting every third value
(take-nth 3 [0 1 2 3 4 5 6 7 8 9]) ;; (0 3 6 9) For a reusable transducer, apply the one-argument form to another process: (into [] (take-nth 2) (range 10)) ;; [0 2 4 6 8]
Building multiples
Because the first selected value is zero, dropping it produces multiples of n: (defn mult-n [n] (rest (take-nth n (range)))) (take 5 (mult-n 11)) ;; (11 22 33 44 55)
