Immutable collectionsλ︎
As we have discussed, immutable data structures cannot be changed. So when you run a function over a collection a copy of that collection is returned. Lets see this by running some code in the REPL.
Note Define a data structure called
numbers
using a vector. Then write a function that uses themap
andinc
function to increment all the numbers in a vector.Then check the current value of the
numbers
data structure by evaluating its name.
;; define the data structure
(defn numbers [1 2 3 4 5])
;; increment the numbers
(map inc numbers)
;; see the current value of numbers
numbers
Note Use the
conj
function to first add the number5
to thenumbers
vector from the previous exercise and check the value ofnumbers
. Then add the number6
to thenumbers
vector and check the value ofnumbers
.Finally, use the
conj
function to add both5
and6
to thenumbers
vector and check the value ofnumbers
(def numbers [1 2 3 4])
;; add 5 to the numbers vector
(conj numbers 5)
;; check the value of numbers
numbers
;; => [1 2 3 4]
;; add 6 to the numbers vector
(conj numbers 6)
;; check the value of numbers
numbers
;; => [1 2 3 4]
;; add 5 and 6 to the numbers vector
(conj numbers 5 6)
;; Alternatively, you can use the threading macro to chain two conj function calls
(-> numbers
(conj 5)
(conj 6))
;; check the value of numbers
numbers
;; => [1 2 3 4]
So even though we have applied several functions on the numbers
data structure it still has the same value.