O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

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

Concise Collection Access

Accessing values is easily the most common operation performed over collections, especially those that support the associative abstraction. That being the case, having to constantly type get or nth could get very tiring. Thankfully, Clojure collections and the most common types of keys used in associative collections are also functions with the semantics of get or nth (as appropriate for the concrete type of collection involved).

Collections are functions. Very simply, Clojure collections are functions that look up the value associated with the key or index that is provided. So these:

(get [:a :b :c] 2)
;= :c
(get {:a 5 :b 6} :b)
;= 6
(get {:a 5 :b 6} :c 7)
;= 7
(get #{1 2 3} 3)
;= 3

are exactly equivalent to these more concise expressions:

([:a :b :c] 2)
;= :c
({:a 5 :b 6} :b)
;= 6
({:a 5 :b 6} :c 7)
;= 7
(#{1 2 3} 3)
;= 3

In each of these cases, the collection is in function position, so it is being called with the key or index to look up within itself. Maps accept an optional second argument just like get, the optional default value returned if the lookup fails. Both vectors and sets accept only a single value/index for the lookup; defaults are not supported. Indices provided for vector lookups must also be within the range of the vector, just as with nth:

([:a :b :c] -1)
;= #<IndexOutOfBoundsException java.lang.IndexOutOfBoundsException>

Collection keys are (often) functions. Similarly, the most common types of keys—keywords and symbols—are also functions ...

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