Vectors are another data structures from the clojure collections. They are indexed and are surrounded by [] brackets and unlike lists they do not need to be quoted.

  [1 2 3]
  ; => [1 2 3]

  ;; another way to creating vectors
  (vector "a" "b" "c")
  ; => [1 2 3]

  (type ["a" "b" "c"])
  ; => clojure.lang.PersistentVector

Important to note that:

  (vector? ["a" "b" "c"])
  ; => true

  ;; vectors are collections
  (coll? ["a" "b" "c"])
  ; => true

  ;; but vectors are not sequential
  (sequential? ["a" "b" "c"])
  ; => true

Vector operations


They are unlike Lists which are sequential, Vectors are both sequential and randomly accessible. Just like Lists, first second and nth work for vectors too.

  (first [1 2 3])
  ; => 1

  (second [1 2 3])
  ; => 2

  (nth [1 2 3] 1)
  ; => 2

Vectors support rseq, get

  ;; rseq - returns the vectors in reverse order
  (rseq ["a" "b" "c"])
  ; => ("c" "b" "a")

  ;; get - works like nth for list
  (get ["a" "b" "c" "d"] 3)
  ; => "d"

And common collection functions like last, count, rest, next

  ;; last - returns the last element
  (last ["a" "b" "c"])
  ; => "c"

  ;; count - returns no. of elements in the vector
  (count ["a" "b" "c"])
  ; => 3

  ; rest - returns all the remaining elements in the collection except the first element
  (rest ["a" "b" "c"])
  ; => ("b" "c")

  ;; next
  (next ["a" "b" "c"])
  ; => ("b" "c")

Wait, whats the difference between rest and next they both seem to do the same thing. The difference lies when there is only single element in the vector/list.

  ;; rest - returns and empty list
  (rest [1])
  ; => ()

  ;; next - returns nil
  (next [1])
  ; => nil

In the next post I will be picking up on yet another collection type in clojure i.e: SETS