Destructuring Data

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​ [[smaller bigger] (​split-with​ #(​<​ % 5) (​range​ 10))]
 
(​println​ smaller bigger))
 
 
=>(0 1 2 3 4) (5 6 7 8 9)

Here we use split-with 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 ones that are greater. Since we know the result’s ...

Get Web Development with Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.