{:check ["true"], :rank ["create" "destructure" "construct"]}

Index

Functions on Vectors

box

Chapter 3.5: Functions on Vectors

Clojure Cheatsheet: https://clojure.org/api/cheatsheet

Create

Creating vectors

In [1]:
; Creating vectors

[3 2 1 "Hello" "World"]
Out[1]:
[3 2 1 "Hello" "World"]
In [4]:
; Using the vector constructor function
(vector 3 2 1 "Hello" "World")
Out[4]:
[3 2 1 "Hello" "World"]
In [2]:
; Convert sequences to vector
(vec '(3 2 1 "Hello" "World"))
Out[2]:
[3 2 1 "Hello" "World"]

Destructure

Destructring

All list destructuring functions can be used for vectors.

In [5]:
; Let's make a vector first.

(def xs [3 2 1 "Hello" "World" :again :and :again])
Out[5]:
#'user/xs
In [6]:
(first xs)
Out[6]:
3
In [7]:
(rest xs)
Out[7]:
(2 1 "Hello" "World" :again :and :again)
In [8]:
(last xs)
Out[8]:
:again
In [9]:
(nth xs 3)
Out[9]:
"Hello"

Vectors are functions

It turns out that vectors can be used as functions over integers.

(xs n)

returns the n-th element.

In [10]:
(xs 3)
Out[10]:
"Hello"

All sequence functions can be applied to vectors.

Construct

Construction

All sequence construction functions can be used for vectors, but with some subtle differences.

In [1]:
; Let's make a vector first.

(def xs [3 2 1 "Hello" "World" :again :and :again])
Out[1]:
#'user/xs

Conj

Recall (conj coll element) addes the element to the collection in the most efficient way.

  • For vectors, element is added to the end of the vector.
  • For lists, element is added to the head of the linked list.
In [2]:
(conj xs "NEW")
Out[2]:
[3 2 1 "Hello" "World" :again :and :again "NEW"]

Into

Same is true for (into coll elements)

In [3]:
(into xs ["NEW-1" "NEW-2" "NEW-3"])
Out[3]:
[3 2 1 "Hello" "World" :again :and :again "NEW-1" "NEW-2" "NEW-3"]

Concat

Concat always returns a list regardless of its input collection types.

In [4]:
(concat xs ["NEW 1" "NEW 2"])
Out[4]:
(3 2 1 "Hello" "World" :again :and :again "NEW 1" "NEW 2")