Sequences - oliyh/learning-clojure GitHub Wiki

Basic operations

Reading an element

(def s [1 2 3])
(get s 1) ;; 2
(s 1) ;; 2

Adding an element at the head

(cons :a [:b :c]) ;; (:a :b :c)

Adding an element at the tail

(conj [:a :b] :c) ;; [:a :b :c]

Concatenation

(concat [:a :b :c] [:d :e :f]) ;; (:a :b :c :d :e :f)

Sub sequences

(butlast [:a :b :c]) ;; (:a :b)
(rest [:a :b :c]) ;; (:b :c)
(take 2 [1 2 3]) ;; (1 2)

The Clojure data structures are immutable, or "persistent". They are not modified by any of these operations, rather a new sequence is returned from these operators. Because they are immutable these operations are cheap.

(def up-to-three [1 2 3])
(conj up-to-three 4) ;; [1 2 3 4]
up-to-three ;; [1 2 3] (unmodified)

List comprehension

Map takes a function f and a sequence, and returns a sequence with f applied to each element of the original.

(defn triple [x] (* 3 x))
(map triple [1 2 3]) ;; (3 6 9)

Reduce takes a function f and a sequence combines all elements of the sequence using f.

(reduce * [1 2 3 4 5]) ;; 120

Filter takes a function f and a sequence, returning a sequence containing elements from the original sequence for which f returned true.

(filter even? [1 2 3 4 5 6]) ;; (2 4 6)

Maps

... are also sequences. For a map, each element is a MapEntry which has the same semantics as a sequence of two elements, [key val].

Reading a key from a map can be done in any of the following ways

(def m {:a 1 :b 2 :c 3})
(get m :b) ;; 2
(m :b) ;; 2
(:b m) ;; 2