liveBook · Manning

Rest

As explained in Clojure: The Essential Reference

rest is a Clojure function that returns a sequence containing all but the first element of a collection, returning an empty sequence when no elements remain.

rest returns a lazy sequence containing every element after the first. It accepts any seqable collection or nil, making it useful for sequential processing and recursive algorithms. section 10.1

Its boundary behavior distinguishes it from related sequence functions:

  • On '(0 1 2 3), rest produces (1 2 3). section 10.1
  • On nil or an empty collection, rest returns an empty list rather than nil. section 10.1
  • Unlike next, rest does not return nil to signal exhaustion; next supports nil punning in recursive conditions. section 10.1

Consume a sequence recursively

(defn rest-loop [coll] (loop [xs coll results []] (if-let [xs (seq xs)] (recur (rest xs) (conj results (first xs))) results))) (rest-loop (range 10)) ;; [0 1 2 3 4 5 6 7 8 9] section 10.1

Listing 10.1. → Seq-in-seq-out, Sequential processing
(rest     [coll])
(next     [coll])
(butlast  [coll])
(nnext    [coll])
(nfirst   [coll])
(fnext    [coll])
(ffirst   [coll])

Use the function listing to compare rest with next, butlast, and the first/next composition helpers. section 10.1

How Clojure: The Essential Reference covers it

How deep it goes
Explains inputs, outputs, empty cases, laziness, recursion, and chunking, while contrasting rest with related functions.
Examples
Uses ordinary sequences, nil, empty collections, recursive loops, lazy traversal, nested data, and chunked versus unchunked mappings.
What it assumes
Assumes familiarity with Clojure collections and sequences while defining seqable inputs and nil or empty behavior.
What you can do after
Apply rest to advance through collections and implement recursive or lazy sequence processors.
How it connects
Connects rest with first, next, lazy sequences, recursion, seqable collections, and sequential processing.

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.