Clojure Destructuring

Destructuring allows to extract values from datastructures and bind them to symbols without explicitly looping/traversing the datastructure. It allows concise and simple coding.

Sequential Destructuring

Provides vector of symbols to bind by position.
Syntax: [symbol another-symbol] [“value” “another-value”]
 (def listNumbers[7 8 9 10 11])
;;Bind a, b, c to first 3 values in stuff
(let [[a b c] listNumbers]
(list (+ a b) (+ b c)))

Result: (15,17)

SequentialDestructuring

It binds to nil if there’s no data, i.e. there are not enough items in the vector to bind to.

(let [[a b c d e f] listNumbers]
(list d e f))

Result : (10 11 nil)

Nil_Destructuring

In the above example there is no data at 6th position in ListNumbers collection to bind to f explaining the nil being returned.

& symbol can get “everything else” with value being a sequence

(def listNumbers[7 8 9 10 11])
(let [[a & others] listNumbers]
(list others))

Result : (8 9 10 11
&_Others

_  symbol is used for values that can be discarded

First element is discarded in the example below

(def listNumbers[7 8 9 10 11])

(let [[_ & others] listNumbers]
(list others)))
)

Result : (8 9 10 11)

_ Discard

Associative Destructuring

Provides map of symbols to bind by key.
Syntax: {symbol :key, another-symbol :another-key} {:key “value” :another-key “another-value”}

(def m {:a 7 :b 4})
(let [{a :a, b :b} m]
[a b])

Result : [7 4]

AssociativeDestructuring

keys  are inferred from vector of symbols to bind

(def m {:a 7 :b 4})
(let [{:keys [a b]} m]
[a b])

Result : [7 4]

Keys_Map

If a key is not found in the map, the symbol is bound to nil.

(let [{:keys [a b c]} m]
[a b c])

Result: [7 4 nil]

Map_Nil

:or provides default values for missing keys with a map of values

(def m {:a 7 :b 4})
(let [{:keys [a b c]
:or {c 3}} m]
[a b c])

Result: [7 4 3]
Or_Map

Named Arguments 
Vector of keys can be bound to & to emulate optional named arguments.

(defn people [planet & {:keys [adults children]}]
(+ adults children))

(people “Earth” :adults 1 :children 5)

Result:6

NamedArguments

Advertisements

2 thoughts on “Clojure Destructuring

  1. Pingback: Links & Reads from 2015 Week 50 – Martin's Weekly Curations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s