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 the map and inc function to increment all the numbers in a vector.

Then check the current value of the numbers data structure by evaluating its name.

  1. ;; define the data structure
  2. (defn numbers [1 2 3 4 5])
  3. ;; increment the numbers
  4. (map inc numbers)
  5. ;; see the current value of numbers
  6. numbers

Note Use the conj function to first add the number 5 to the numbers vector from the previous exercise and check the value of numbers. Then add the number 6 to the numbers vector and check the value of numbers.

Finally, use the conj function to add both 5 and 6 to the numbers vector and check the value of numbers

  1. (def numbers [1 2 3 4])
  2. ;; add 5 to the numbers vector
  3. (conj numbers 5)
  4. ;; check the value of numbers
  5. numbers
  6. ;; => [1 2 3 4]
  7. ;; add 6 to the numbers vector
  8. (conj numbers 6)
  9. ;; check the value of numbers
  10. numbers
  11. ;; => [1 2 3 4]
  12. ;; add 5 and 6 to the numbers vector
  13. (conj numbers 5 6)
  14. ;; Alternatively, you can use the threading macro to chain two conj function calls
  15. (-> numbers
  16. (conj 5)
  17. (conj 6))
  18. ;; check the value of numbers
  19. numbers
  20. ;; => [1 2 3 4]

So even though we have applied several functions on the numbers data structure it still has the same value.