Skip to content

Instantly share code, notes, and snippets.

@leobm
Forked from anonymous/gist:5335938
Created April 8, 2013 10:58
Show Gist options
  • Save leobm/5335942 to your computer and use it in GitHub Desktop.
Save leobm/5335942 to your computer and use it in GitHub Desktop.
;; by John Lawrence Aspden - http://www.learningclojure.com/2013/04/destructuring.html
;; Destructuring
;; One of Clojure's great strengths is the ability to create maps ad-hoc and to deal with them easily.
;; You can create an ad-hoc structure with named fields:
{:a 3 :b 1}
;; And unpack it, providing defaults for its values if they are not present, as easily as:
(defn add-maps [{:keys [a b] :or {a 0 b 0} }]
(+ a b))
(add-maps {:a 3 :b 1}) ;-> 4
(add-maps {:a 3}) ;-> 3
(add-maps {}) ;-> 0
(add-maps {:c "hello"}) ;-> 0
;; I love this and use it all the time. It's well worth learning the syntax.
;; Try playing with this expression:
(take 5 (iterate (fn [{:keys[a b] :or {b 55} :as m}] {:a a :b b :m m}) {:a 0 :b 0}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment