Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Clojure Programming Cookbook

You're reading from   Clojure Programming Cookbook Handle every problem you come across in the world of Clojure programming with this expert collection of recipes

Arrow left icon
Product type Paperback
Published in Oct 2016
Publisher Packt
ISBN-13 9781785885037
Length 618 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Nicolas Modrzyk Nicolas Modrzyk
Author Profile Icon Nicolas Modrzyk
Nicolas Modrzyk
Makoto Hashimoto Makoto Hashimoto
Author Profile Icon Makoto Hashimoto
Makoto Hashimoto
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Live Programming with Clojure FREE CHAPTER 2. Interacting with Collections 3. Clojure Next 4. File Access and the Network 5. Working with Other Languages 6. Concurrency and Parallelism 7. Advanced Tips 8. Web Applications 9. Testing 10. Deployment and DevOps

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 (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) 
;;...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime