Monday, September 07, 2020

#100DaysOfClojure (Day [8] Vectors)

Vector is another collection data structure that allow random access and add new elements to the end of the collection. 


Here is an example of how you declare a vector:

[1 "Hello" :anytype 22/7]
=> [1 "Hello" :anytype 22/7]

or alternatively

(vector 1 "Hello" :anytype 22/7)
=> [1 "Hello" :anytype 22/7]

You can retrieve any element by using its index which is zero based

(get [1 "Hello" :anytype 22/7] 1)
=> "Hello"

You can get a count of elements as follows

(count [1 "Hello" :anytype 22/7])
=> 4

You can add elements as follows:

(conj [1 "Hello" :anytype 22/7] 2.25)
=> [1 "Hello" :anytype 22/7 2.25]

You can remove an element from the end of the Vector as follows :

(pop [1 "Hello" :anytype 22/7 2.25])
=> [1 "Hello" :anytype 22/7]
 
You can also remove a subset of elements from the vector as follows:

(subvec [1 "Hello" :anytype 22/7 2.25] 1 3)
=> ["Hello" :anytype]
Note the start index is inclusive while the end index is exclusive.

You could also use the nth function as follows:

(nth [1 "Hello" :anytype 22/7 2.25] 2)
=> :anytype

You could also replace values in a Vector using the assoc function

(assoc [1 "Hello" :anytype 22/7 2.25] 1 2 2 3)
=> [1 2 3 22/7 2.25]


That's all on Vectors, tomorrow I will look at Map Collections

(println "Bye 4 Now!")

No comments: