What is the vector nth method in Clojure?

What is a vector in Clojure?

A vector is a Clojure data structure that stores sequentially indexed data.

Let's look at the nth vector method in detail.

Syntax

(nth vec index)

Parameters

The nth method receives two parameters:

  1. vec: This is the vector containing a list of elements.
  2. index: This is the position where a particular element is placed in the vector.

Return value

The method returns an element from the vector located at the index position.

Example

(ns clojure.examples.example
(:gen-class))
(defn nthh []
(println (nth (vector 5 4 3 2 1) 3))
(println (nth (vector 5 4 4 2 1) 1)))
(nthh)

Explanation

From the code above:

  • Line 3: We define a function nthh.
  • Line 4: We print the element returned using println. We use the nth method to get the value at the index position 3 from the vector.
  • Line 5: We print the element returned using the println. Again, we use the nth method to get the value at the index position 1 from the vector.
  • Line 6: We call the nthh function.
Note: The nth method and the get method are very similar in their functionality.

Free Resources