liveBook · Manning

Nth

As explained in Clojure: The Essential Reference

nth is a Clojure function that returns the element at a numeric index in an indexed or sequential collection, optionally returning a fallback when the index is absent.

nth returns the value at a numeric index in an indexed or sequential collection. Use its two-argument form when a missing index should fail, or provide a fallback with the three-argument form. section 8.1.3 section 12.2

Keep these contracts and performance differences in mind:

  • Returns the element at the requested index when present. section 8.1.3
  • Throws IndexOutOfBoundsException for an absent index without a fallback; returns not-found when supplied instead. section 8.1.3
  • Accepts nil as a collection, returning nil or the supplied fallback. section 8.1.3
  • Works with vectors, sub-vectors, primitive and transient vectors, native arrays, sequences, lists, queues, ranges, strings, and ArrayList; it does not work on maps or sets. section 8.1.3
  • Provides O(1) access for vectors and arrays, but can require O(n) traversal for lists, queues, and ranges. section 8.1.3
  • Truncates decimal indexes to integers; Double/NaN selects the first element when one exists, while values above Integer/MAX_VALUE are illegal. section 8.1.3

Fallback versus exception

(nth [0 1 2 3 4] 2) ;; 2 (nth [] 2) ;; IndexOutOfBoundsException (nth [] 2 :missing) ;; :missing (nth nil :missing) ;; :missing section 8.1.3

Indexed lookup in a vector-backed hash table

A vector can store values at hash-derived positions. After keys are converted to indexes and entries assigned, fetch retrieves a value with nth: (fetch (put ht :c 3) :b) ;; 2 section 8.1.3

Listing 8.3. → Data Access, Indexed Lookup
(nth
  ([coll index])
  ([coll index not-found]))

Use the signature to compare the required collection and index arguments with the optional fallback argument. section 8.1.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines arities, return behavior, exceptions, numeric edge cases, supported collections, and access complexity.
Examples
Demonstrates vector lookup, missing-index fallbacks, nil handling, and vector-backed hash-table retrieval.
What it assumes
Assumes familiarity with Clojure collections, numeric indexes, and vector or sequence access.
What you can do after
Apply it via Clojure to retrieve indexed values and choose explicit behavior for absent positions.
How it connects
Contrasts nth with get and relates it to vectors, sequences, arrays, maps, and sets.

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.