liveBook · Manning

Take-nth

As explained in Clojure: The Essential Reference

take-nth is a Clojure function and transducer that selects every nth element from a sequential input.

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)

How Clojure: The Essential Reference covers it

How deep it goes
Defines both arities, lazy output, transducer behavior, and corner-case exceptions, but does not develop implementation internals.
Examples
Demonstrates regular sampling, transducer application with into, and generating multiples from an infinite range.
What it assumes
Assumes familiarity with sequential collections, lazy sequences, optional arguments, and transducer-consuming operations.
What you can do after
Apply it via Clojure sequence functions or transducer operations to retain regularly spaced input elements.
How it connects
Connects sequential processing with lazy sequences, filtering by index, transducers, and reducing functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.