14. Destructuring - Koans Walkthrough

This video introduces destructuring, which provides a concise way to initialize multiple variables with values from a complex structure. It is also called "abstract structural binding", destructuring bind or destructuring assignment. We'll learn how it can help us make our code more elegant.

Here is the 14_destructuring.clj source code:

(def test-address
  {:street-address "123 Test Lane"
   :city "Testerville"
   :state "TX"})

  "Destructuring is an arbiter: it breaks up arguments"
  (= __ ((fn [[a b]] (str b a))
         [:foo :bar]))

  "Whether in function definitions"
  (= (str "First comes love, "
          "then comes marriage, "
          "then comes Clojure with the baby carriage")
     ((fn [[a b c]] __)
      ["love" "marriage" "Clojure"]))

  "Or in let expressions"
  (= "Rich Hickey aka The Clojurer aka Go Time aka Macro Killah"
     (let [[first-name last-name & aliases]
           (list "Rich" "Hickey" "The Clojurer" "Go Time" "Macro Killah")]

  "You can regain the full argument if you like arguing"
  (= {:original-parts ["Steven" "Hawking"] :named-parts {:first "Steven" :last "Hawking"}}
     (let [[first-name last-name :as full-name] ["Steven" "Hawking"]]

  "Break up maps by key"
  (= "123 Test Lane, Testerville, TX"
     (let [{street-address :street-address, city :city, state :state} test-address]

  "Or more succinctly"
  (= "123 Test Lane, Testerville, TX"
     (let [{:keys [street-address __ __]} test-address]

  "All together now!"
  (= "Test Testerson, 123 Test Lane, Testerville, TX"
     (___ ["Test" "Testerson"] test-address)))

Clojure Koans Walkthrough in Light Table IDE

This screencast tutorial helps you learn the Clojure programming language. Experience the joy of Clojure in the Light Table IDE as we tour through the Clojure Koans, taking you all the way from Beginner to Intermediate to Advanced.

Clojure is a Lisp created by Rich Hickey that runs on the JVM, as an alternative to Java. ClojureScript can target the web browser environment, and node.js, by compiling down to JavaScript, using the Google Closure compiler. Clojure features immutability, functional programming, and being a Lisp, macros.