Destructuring in Clojure.
Clojure desctructuring) - Clojure supports abstract structural binding, often called destructuring, in let binding lists, fn parameter lists, and any macro that expands into a let or fn. The basic idea is that a binding-form can be a data structure literal containing symbols that get bound to the respective parts of the init-expr. The binding is abstract in that a vector literal can bind to anything that is sequential, while a map literal can bind to anything that is associative.
Sequential binding destructuring
More often called "Vector binding destructuring" this allows us to bind names to parts of sequential things.
A typical example may be.
Here we assign the names a, b and c to the items in a vector. The example above outputs `[1 2 3]```.
We can also capture parts of a sequential item and make the item as a whole available.
Here we capture the first two parts of the sequence as a and b while making available the whole sequence :as
v. The example above outputs `{:a 1 :b 2 :v [1 2 3 4 5]}```
Sequential binding destructuring is not limted to vectors or lists, it can be used for anything that supports `nth```.
We can use it on strings.
Again we capture the first two parts of the sequence as a and b while making available the whole sequence :as
s. The example above outputs `{:a \d :b \e :s "destructuring"}```.
Map binding destructuring
This allows us to bind names to parts of a map.Here we capture the values of the :a
and :b
keys from the map. This outputs `30```.
The same principals discussed in relation to sequential binding apply to map binding as well.
So, we can make available the whole map as follows.
Again we capture :a
and :b
but we also make the whole map available using :as
m.
When we want to desctructure to bindings with the same name as map keys we can make this more concise by using `:keys```.
Destructuring function arguments
We can also destructure function arguments. As an example we can define a function like so.
Then we can call it.
We can use what we learnt above to make available the whole map as well.
Now we can call it like this.
What if we want to apply some default values?
We can use :or
to define default values to use if the keys are not present in the map.
We can call it like this.
We can even add :pre
conditions based on the destructures.
Calling like so will result in a AssertionError
.