liveBook · Manning

Nthrest

As explained in Clojure: The Essential Reference

nthrest is a Clojure function that removes a specified number of elements from the beginning of a sequence and returns an empty list when the sequence is exhausted.

`nthrest` skips a specified number of elements at the head of a sequence and returns the remaining suffix. Call it as `(nthrest coll n)`, where `coll` is seqable or nil and `n` is a number. A zero or negative count skips nothing. If the input is exhausted, the result is an empty sequence, never nil. An input that cannot be sequenced causes an `IllegalArgumentException`. section 10.2

Skip a prefix

(nthrest [10 20 30 40] 2) ; => (30 40) (nthrest [10 20] 9) ; => () (nthrest [10 20] -1) ; => (10 20) (nthrest nil 2) ; => () section 10.2

`drop` performs the same kind of prefix removal but takes its arguments in the opposite order: `(drop n coll)`. Unlike `drop`, `nthrest` has no transducer form and evaluates the elements it skips when called. Unlike `nthnext`, it returns an empty sequence rather than nil when it runs past the input. section 10.2

Skipping can trigger work

(defn xs [] (map #(do (print ".") %) (iterate inc 0))) (def tail (nthrest (xs) 3)) ; prints ... The three dots appear while `tail` is defined: skipping the first three generated values evaluates them. This matters when producing values has side effects. section 10.2

To inspect every possible starting position in a stream of rows, map `nthrest` over successive offsets. Each result is a suffix that can then be filtered for a desired row pattern. section 9.1.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines arguments, exhaustion behavior, and partial evaluation with an observable example; does not develop implementation internals.
Examples
Shows skipped values printing dots and skipped file-processing steps causing side effects; uses suffixes to find device-output patterns.
What it assumes
Assumes familiarity with Clojure function calls and sequences; states the skip-count contract without requiring transducer knowledge.
What you can do after
Apply it via Clojure’s sequence API to skip prefixes and generate suffixes while accounting for evaluation of skipped elements.
How it connects
Contrasts drop, nthnext, and transducers, and combines suffix generation with sequence-based pattern filtering.

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.