Skip to main content

Data Structures

Beginner 4 min read Last updated
On this page

All Phel collections are persistent: they never change. An update returns a new collection that shares most of its structure with the old one, so updates stay cheap and the original stays valid.

(def config {:theme "dark" :lang "en"})
(def new-config (assoc config :theme "light"))

config     ; => {:theme "dark" :lang "en"}
new-config ; => {:theme "light" :lang "en"}
PHP Coming from PHP?

PHP arrays copy on write, and code that holds a reference can change them in place. A Phel function can never change the data you pass to it. When you need a mutable PHP array for interop, create one with (php/array) and change it with php/aset.

Choosing a collection

CollectionLiteralUse it for
Vector[1 2 3]ordered values, access by index, append at the end
Map{:a 1 :b 2}values looked up by key
Set#{1 2 3}unique values, fast membership tests
List'(1 2 3)code as data, adding at the front
Queue(queue 1 2 3)first in, first out

Vectors

A vector is an indexed sequence. Reading by index and appending at the end are fast.

(vector 1 2 3) builds one from arguments and (vec '(1 2 3)) from any collection. Read by index with get (or nth). get returns nil, or a default, when the index is missing:

(get [10 20 30] 0)       ; => 10
(get [10 20 30] 5)       ; => nil
(get [10 20 30] 5 :none) ; => :none
(first [10 20 30])       ; => 10
(peek [10 20 30])        ; => 30 (the last element)

Add at the end with conj. Replace by index with assoc. Drop the last element with pop:

(conj [1 2 3] 4)     ; => [1 2 3 4]
(assoc [1 2 3] 0 9)  ; => [9 2 3]
(assoc [1 2 3] 3 4)  ; => [1 2 3 4] (one past the end appends)
(pop [1 2 3])        ; => [1 2]
(count [1 2 3])      ; => 3

Maps

A map stores key-value pairs, each key once. Keys are usually keywords, but any value can be a key.

Build one with a literal, {:name "Alice" :age 30}, or with hash-map. Read with get, or call the keyword as a function. Both accept a default:

(get {:a 1 :b 2} :a)      ; => 1
(get {:a 1 :b 2} :c 0)    ; => 0
(:a {:a 1 :b 2})          ; => 1
(contains? {:a 1} :a)     ; => true

Add or replace keys with assoc. Remove them with dissoc. Combine maps with merge, where later maps win:

(assoc {:a 1} :b 2 :c 3)          ; => {:a 1 :b 2 :c 3}
(dissoc {:a 1 :b 2 :c 3} :a :c)   ; => {:b 2}
(merge {:theme "light" :lang "en"} {:theme "dark"})
; => {:theme "dark" :lang "en"}

keys, vals, and select-keys read parts of a map: (select-keys {:a 1 :b 2 :c 3} [:a :c]) returns {:a 1 :c 3}.

Calling seq or first on a map gives map entries, which are equal to [key value] vectors: (first {:a 1}) returns [:a 1].

Sets

A set holds unique values. Testing membership is fast.

#{1 2 3}          ; literal
(hash-set 1 2 3)  ; => #{1 2 3}, from arguments
(set [1 1 2 3])   ; => #{1 2 3}, from a collection

(conj #{1 2} 3)           ; => #{1 2 3}
(conj #{1 2} 2)           ; => #{1 2} (already present)
(disj #{1 2 3} 2)         ; => #{1 3}
(contains? #{1 2 3} 2)    ; => true

Set algebra is in core: union, intersection, difference, subset?, and superset?. For example, (union #{1 2} #{2 3}) returns #{1 2 3}. See the core API.

Lists

A list is a linked list. Adding and reading at the front is fast. Reading by index is slow. Phel code is itself written as lists, so quote a list to keep it as data:

'(1 2 3)          ; => (1 2 3)
(list 1 2 3)      ; => (1 2 3)
(first '(1 2 3))  ; => 1
(rest '(1 2 3))   ; => (2 3)
(conj '(1 2 3) 0) ; => (0 1 2 3), adds at the front

rest returns an empty collection when nothing is left. next returns nil, which is handy in a loop test.

Queues

A queue is first in, first out. conj adds at the back. peek reads the front and pop removes it. There is no literal; build one with queue:

(def q (queue 1 2 3))
(peek q)   ; => 1
(conj q 4) ; => <-(1 2 3 4)-<
(pop q)    ; => <-(2 3)-<

A queue prints as <-(...)-<: items enter on the right and leave on the left.

Working with collections

Adding with conj

conj adds where it is cheapest for the type:

Typeconj addsExample
Vectorat the end(conj [1 2] 3) => [1 2 3]
Listat the front(conj '(1 2) 0) => (0 1 2)
Setif not present(conj #{1} 2) => #{1 2}
Mapa [key value] pair(conj {:a 1} [:b 2]) => {:a 1 :b 2}

Nested data

The -in functions take a path of keys and indexes:

(def user {:name "Alice"
           :settings {:theme "dark" :font-size 14}})

(get-in user [:settings :theme])               ; => "dark"
(get-in user [:settings :missing] "default")   ; => "default"
(assoc-in user [:settings :theme] "light")
; => {:name "Alice" :settings {:theme "light" :font-size 14}}
(update-in user [:settings :font-size] + 2)
; => {:name "Alice" :settings {:theme "dark" :font-size 16}}

update applies a function to one value. Extra arguments go after the old value:

(update {:count 1} :count inc) ; => {:count 2}
(update [1 2 3] 0 + 10)        ; => [11 2 3]

update-vals applies a function to every value of a map, and update-keys to every key: (update-vals {:a 1 :b 2} inc) returns {:a 2 :b 3}.

Building with into

into adds every element of one collection to another. Use it to convert between types:

(into [] '(1 2 3))         ; => [1 2 3]
(into #{} [1 2 2 3])       ; => #{1 2 3}
(into {} [[:a 1] [:b 2]])  ; => {:a 1 :b 2}

Transducers

into also takes a transformation as its middle argument: (into [] (map inc) [1 2 3]) returns [2 3 4]. See Transducers.

Data structures as functions

Lists, vectors, maps, and sets are functions of their keys. Keywords are functions of maps. This keeps lookups short, especially with map:

([10 20 30] 1)    ; => 20
({:a 1 :b 2} :a)  ; => 1
(#{1 2 3} 2)      ; => 2
(#{1 2 3} 4)      ; => nil

(map :name [{:name "Alice"} {:name "Bob"}]) ; => ("Alice" "Bob")

Structs

A struct is a map with a fixed set of keys and a name. defstruct defines a constructor and a predicate:

(defstruct point [x y])

(def p (point 1 2))
(point? p)       ; => true
(get p :x)       ; => 1
(:y p)           ; => 2
(assoc p :x 10)  ; => (user.point 10 2)

A struct compiles to a PHP class with one property per key, so it is faster than a map. PHP code can call count($p) and read $p['x']: every struct implements \Countable, \ArrayAccess, and \IteratorAggregate.

A :php block adds PHP magic methods such as __invoke and __toString. The first argument is the struct itself:

(defstruct multiplier [factor]
  :php
  (__invoke   [this x] (* x (get this :factor)))
  (__toString [this]   (str "x" (get this :factor))))

((multiplier 3) 14) ; => 42

A custom __invoke must take exactly one argument or be variadic, because a struct is already callable as a key lookup. Implementing interfaces on structs: Interfaces.

Transients

transient turns a vector, map, or set into a mutable builder, and persistent turns it back. Both conversions are cheap. Use one only inside a single function, never share it.

Walking data structures

phel.walk transforms every level of nested data: postwalk, prewalk, and keywordize-keys (handy for decoded JSON). See the walk API.

Practice

Try what this page covers in Collections.