Destructuring Data

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (75 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Structuring th e Code | TOC | Namespaces 👉

Clojure has a powerful mechanism called destructuring for declaratively accessing values in data structures. If you know the data structure’s type, you can describe it using a literal notation in the binding. Let’s look at some examples of what this means.

​ (​let​ [[small big] (split-with #(< % 5) (range 10))]
​ (println small big))

​ =>(​0​ 1 2 3 4) (​5​ 6 7 8 9)

Here we use the split-with function to split a range of ten numbers into a sequence containing two elements: numbers less than 5 and numbers greater than or equal to 5. The split-with function returns a sequence containing two elements: the first is the sequence of items that are less than 5, and the other is the sequence that is greater than or equal to 5. Since we know the result’s format, we can write it in a literal form as [small big] and then use these named elements within the let binding.

We can use this type of destructuring in function definitions as well. Let’s say we have a function called print-user that accepts a vector with three items. It names the items name, address, and phone, respectively.

​ (​defn​ print-user [[name address phone]]
​ (println name address phone))
​ (​print-user​ [​"Bob"​ ​"12 Jarvis street, Toronto"​ ​"416-987-3417"​])

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.