concept nth in category clojure

appears as: nth, nth
Clojure: The Essential Reference

This is an excerpt from Manning's book Clojure: The Essential Reference.

  • “nth” is a general way to access an element by index in a collection.
  • nth returns the value found at the specified index from the collection passed as argument:

    (let [coll [0 1 2 3 4]]
      (nth coll 2))
    ;; 2

    nth throws error in case the index doesn’t exist (instead of returning nil (as get would instead do for sequential access). nth doesn’t throw exception when a default value is provided:

    (nth [] 2) ; #1
    ;; IndexOutOfBoundsException
    
    (nth [] 2 0) ; #2
    ;; 0

    nth is specifically designed for data structures offering random access lookup like vectors, sub-vectors, primitive vectors and transient vectors. It also handles native arrays and Java arrays with the same efficiency. nth can makes access to sequences although, in this case, less efficiently. It does not work at all on associative data structures (e.g. maps, sets and related ordered variants) for which a dedicate alternative exists (get).