Learn clojure in Y minutes - Collections and Sequences

The following is from Learn clojure in Y minutes.

list - a linked list data structure

vector - an array data structure

These are java classes too:

> (class '(1 2 3))
    clojure.lang.PersistentList
    
    > (class (list 1 2 3))
    clojure.lang.PersistentList
    
    > (class [1 2 3])
    clojure.lang.PersistentVector

Lists and vectors are collections.

collection - a group of data

> (coll? '(1 2 3))
    true
    
    > (coll? [1 2 3])
    true

Only lists are sequences.

sequence - abstract description of a list of data

> (seq? '(1 2 3))
    true
    
    > (seq? [1 2 3])
    false

You only need to provide an entry to a sequence when it is accessed.

> (range 4)
    (0 1 2 3)
    
    > (take 4 (range))
    (0 1 2 3)

Because of this, seqs can be lazy.

lazy seq - defines an infinite series

> (range)
    OutOfMemoryError Java heap space  java.util.Arrays.copyOf (Arrays.java:2882)

cons - add an item to the beginning of a list or vector

> (cons 4 '(1 2 3))
    (4 1 2 3)
    
    > (cons 4 [1 2 3])
    (4 1 2 3)

conj - adds an item to a collection in the most efficient way

For lists, the item is inserted to the beginning.

> (conj 4 '(1 2 3))
    ClassCastException java.lang.Long cannot be cast to clojure.lang.IPersistentCollection  clojure.core/conj (core.clj:83)

Oops.

> (conj '(1 2 3) 4)
    (4 1 2 3)

For vectors, the item is added to the end.

> (conj 4 [1 2 3])
    ClassCastException java.lang.Long cannot be cast to clojure.lang.IPersistentCollection  clojure.core/conj (core.clj:83)
    
    > (conj [1 2 3] 4)
    [1 2 3 4]

This operation is not commutative.

concat - adds lists or collections together

> (concat [1 2] '(3 4))
    (1 2 3 4)

To interact with collections, you can use functions like filter or map.

> (filter even? '(1 2 3))
    (2)
    
    > (map inc [1 2 3])
    (2 3 4)
    
    > (map inc (range 5)
    (1 2 3 4 5)

reduce - used to reduce collections

The following distributes the + over each thing in the vector:

> (reduce + [1 2 3 4]) ; (+ (+ (+ 1 2) 3) 4)
    10

reduce can also take three arguments, with the first argument defining an initial value. The following turns the list

'(3 2 1)
into a vector:

> (reduce conj [] '(3 2 1))
    ; (conj (conj (conj [] 3) 2) 1)
    [3 2 1]

Published January 05, 2015