Lists

You can change lists with the cons function, see (doc cons) for details

(cons 5 ‘(1 2 3 4))

You will see that cons does not change the existing list, it create a new list that contains the number 5 and a link to all the elements of the existing list.

You can also use cons on vectors (cons 5 [1 2 3 4])

  1. (cons "fish" '("and" "chips"))
  2. (conj '(1 2 3 4) 5)
  3. (conj [1 2 3 4] 5)
  4. ;; Lets define a simple list and give it a name
  5. (def list-one '(1 2 3))
  6. ;; the name evaluates to what we expect
  7. list-one
  8. ;; If we add the number 4 using the cons function, then we
  9. ;; get a new list in return, with 4 added to the front (because thats how lists work with cons)
  10. (cons 4 list-one)
  11. ;; If we want to keep the result of adding to the list, we can assign it a different name
  12. (def list-two (cons 4 list-one))
  13. ;; and we get the result we want
  14. list-two
  15. ;; we can also assing the original name we used for the list to the new list
  16. (def list-one (cons 4 list-one))
  17. ;; If we re-evaluate the definition above, then each time we will get an extra
  18. ;; number 4 added to the list.
  19. list-one
  20. ;; Again, this is not changing the original list, we have just moved the name
  21. ;; of the list to point to the new list.
  22. ;; Any other function working with this data structure before reassigning the name
  23. ;; will not be affected by the re-assignment and will use the unchanged list.