O'Reilly logo

Clojure Programming Cookbook by Nicolas Modrzyk, Makoto Hashimoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required