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
