Learn/Clojure/7. Vectors and maps
Lesson 7 of 8
Sign in

Clojure, lesson 7

Vectors and maps

Clojure is built around a handful of immutable collections and a large library of functions that work on all of them. Learn a few of each and you can solve most everyday problems without writing a single loop.

Vectors and lists

A vector is an ordered collection written in square brackets. It is the collection you will use most:

(def scores [12 7 30])

(count scores)        ; 3
(first scores)        ; 12
(get scores 1)        ; 7   (positions start at 0)
(conj scores 99)      ; [12 7 30 99]  (adds at the end)

conj returns a new vector; scores itself is still [12 7 30]. Clojure shares the unchanged parts between the old and new versions, so this is cheap.

A list, written '(1 2 3), also holds items in order, but conj adds to the front of it. Lists are mostly used for code itself; for data, prefer vectors.

Sequence functions

Most collection functions treat their input as a sequence: something with a first item and the rest. That is why the same functions work on vectors, lists, strings, maps and lines of input:

reduce combines the items one at a time with a function: (reduce + [4 10 3 8]) computes ((4 + 10) + 3) + 8. apply calls a function with the items of a collection as its arguments, so (apply max [4 10 3]) is (max 4 10 3).

Long chains read well with the thread-last macro ->>, which passes each result as the last argument of the next step:

line-seq gives you all input lines as a sequence: (line-seq (java.io.BufferedReader. *in*)). From there, every sequence function applies.

Maps

A map stores key → value pairs in curly braces. Keys are often keywords, but strings and numbers work too:

Again, nothing is modified in place: assoc and update return new maps.

Looping over a map gives you [key value] pairs, which you can unpack right in the binding:

Regular maps have no particular order, so sort them when the order of the output matters.

Counting with frequencies

Counting how often each item appears is so common that Clojure has a function for it:

Further reading

  • Learn Clojure: Sequential Collections
  • Learn Clojure: Hashed Collections
  • Threading Macros Guide

2 exercises to try what you just read.

Exercise 1

Score summary

Read one line of whole numbers separated by spaces (there is at least one). Print how many there are, their total and the largest one.

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

Exercise 2

Vote counter

Each line of input is one vote: the name of a candidate. Count the votes and print each candidate with their number of votes, in alphabetical order, one per line.

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

(def prices [4 10 3 8])

(map #(* % 2) prices)        ; (8 20 6 16)
(filter #(< % 5) prices)     ; (4 3)
(reduce + prices)            ; 25
(apply max prices)           ; 10
(sort prices)                ; (3 4 8 10)
(->> prices
     (filter #(> % 3))
     (map #(* % 2))
     (reduce +))             ; 44
(def stock {"apples" 12, "pears" 4})

(get stock "apples")          ; 12
(get stock "plums" 0)         ; 0   (default when the key is missing)
(assoc stock "plums" 9)       ; a new map with plums added
(update stock "pears" inc)    ; a new map with pears = 5
(keys stock)                  ; ("apples" "pears")
(doseq [[fruit n] (sort stock)]
  (println fruit n))
(frequencies ["red" "blue" "red"])    ; {"red" 2, "blue" 1}
12 7 30 1
Count: 4
Total: 50
Max: 30
Mila
Theo
Mila
Ava
Ava 1
Mila 2
Theo 1