In this recipe, we will teach you how to access elements and update elements in collections.
You only need REPL, as described in the recipe in Chapter 1, Live Programming with Clojure, and no additional libraries. Start REPL so that you can review the sample code in this recipe.
Let's start with accessing collections.
nth
gets the nth
element from collections. The second argument of nth
starts from 0 and throws an exception if the second argument is larger than the number of elements minus 1:
(nth [1 2 3 4 5] 1) ;;=> 2 (nth '("a" "b" "c" "d" "e") 3) ;;=> "d" (nth [1 2 3] 3) ;;=> IndexOutOfBoundsException clojure.lang.PersistentVector.arrayFor (PersistentVector.java:153)
If you would like to avoid such an exception, use the third argument as the return value:
(nth [1 2 3] 3 nil) ;;=> nil
Notice that nth
does not...