Learning Clojure/Collection functions

Collection functionsEdit

The clojure namespace contains many functions and macros for handling collections. Rather than repeat reference information from the API documentation, I'll give just a few example operations:

  • (count collection)

Returns the number of items in the collection.

(count [a b c])  ; return 3
(count nil)      ; return 0
  • (conj collection item)

conjoin. Returns a new copy of the collection with the item added. How the item is added depends upon the collection type, e.g. an item conjoined to a list is added to the beginning while an item conjoined to a vector is added to the end.

(conj [5 7 3] 9)        ; returns [5 7 3 9]
(conj (list 5 7 3) 9))  ; returns list (9 5 7 3)
(conj nil item)         ; returns list (item) 
  • (list item*)
  • (vector item*)
  • (hash-map keyval*) where keyval => key value

Produce a list, vector, or hashmap, respectively. You can generally always just use literal syntax in place of these functions, but having functions gives us something to pass to other functions expecting function arguments.

  • (nth collection n)

Return the nth item from collection, where collection is any collection but not a map. (The collection can be a sequence over a map, but not an actual map.)

(nth [31 73 -11] 2)        ; returns -11  
(nth (list 31 73 -11) 0)   ; returns 31
(nth [8 4 4 1] 9)          ; exception: out of bounds
  • keywords as functions

A keyword can be used as a function to look up a key's value in the various kinds of maps (hashmaps, sets, structmaps, etc.):

(:velcro {:velcro 5 :zipper 7})   ; returns 5, the value mapped to :velcro in the hashmap
  • maps as functions

The map types themselves can be used as functions to look up their key's values:

({:velcro 5 :zipper 7} :velcro)   ; returns 5, the value mapped to :velcro in the hashmap
({3 "cat" :tim "moose"} :tim)     ; returns "moose", the value mapped to :tim in the hashmap
(["hi" "bye"] 1)                  ; returns "bye", the value of the second index in the vector


Sequence functionsEdit

Most of the sequence functions can be passed objects which are not sequences but from which a sequence can be derived, e.g. you can pass a list in place of a sequence.

Where there are redundancies between sequence operations and more operations specialized for specific collection types, the redundancies are mostly for performance considerations. For instance, to produce a reversed-order sequence of a vector, you can use the sequence operation reverse or the vector specific rseq: while rseq is less general, it is more efficient.

  • (seq collection)

Return a sequence representing the collection. seq also works on native Java arrays, Strings, and any object that implements Iterable, Iterator, or Enumeration.