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
numbersusing a vector. Then write a function that uses themapandincfunction to increment all the numbers in a vector.Then check the current value of the
numbersdata 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
conjfunction to first add the number5to thenumbersvector from the previous exercise and check the value ofnumbers. Then add the number6to thenumbersvector and check the value ofnumbers.Finally, use the
conjfunction to add both5and6to thenumbersvector 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.