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:
vec: This is the vector containing a list of elements.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 thenthmethod to get the value at theindexposition3from thevector. - Line 5: We print the element returned using the
println. Again, we use thenthmethod to get the value at theindexposition1from thevector.
- Line 6: We call the
nthhfunction.
Note: Thenthmethod and thegetmethod are very similar in their functionality.