Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a specific element in a vector of vectors clojure

Tags:

vector

clojure

If I have a vector defined as

(def matrix [[1 2 3][4 5 6]])

How in clojure do I access a random element in a vector of vectors? I keep seeing people say online that one of the benefits to using a vector over a list is that you get random access instead of having to recurse through a list but I haven't been able to find the function that allows me to do this. I'm used to in c++ where I could do matrix[1][1] and it would return the second element of the second vector.

Am I stuck having to loop one element at a time through my vector or is there an easier way to access specific elements?

like image 890
user1443362 Avatar asked Feb 07 '14 20:02

user1443362


People also ask

How do you access individual elements of a vector?

Vector elements are accessed using indexing vectors, which can be numeric, character or logical vectors. You can access an individual element of a vector by its position (or "index"), indicated using square brackets. In R, the first element has an index of 1.

What is a clojure vector?

Advertisements. A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.


1 Answers

Almost like you would do it in C++:

user=> (def matrix [[1 2 3][4 5 6]])
user=> (matrix 1)
[4 5 6]
user=> ((matrix 1) 1)
5

As the docs say:

Vectors implement IFn, for invoke() of one argument, which they presume is an index and look up in themselves as if by nth, i.e. vectors are functions of their indices.

like image 167
bereal Avatar answered Oct 30 '22 09:10

bereal