Accessing and updating elements from collections

In this recipe, we will teach you how to access elements and update elements in collections.

Getting ready

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.

How to do it...

Let's start with accessing collections.

Accessing collections using the nth function

nth gets the nthelement 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 ...

Get Clojure Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.