Clojure Koan 15: Destructuring

I am working through the Clojure koans.

I found a guy who did them and put his answers on github (username viebel), and when I am done I check mine against his. I found out you can also look at resources/koans.clj for answers, but they are formatting oddly in that file.

Koan 15 is about destructuring. Some of the problems use a map that is provided in the beginning:

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

Here is the original problem:

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

Here is my answer:

(= "Test Testerson, 123 Test Lane, Testerville, TX"
   ((fn [xstr ymap]
     (let [ {street-address :street-address, city :city, state :state} ymap ]
       (str (clojure.string/join " " xstr ) ", " street-address ", " city ", " state ))) ["Test" "Testerson"] test-address))

Here is the more elegant answer:

(= "Test Testerson, 123 Test Lane, Testerville, TX"
     ((fn[[a b] {:keys [street-address city state]}] 
        (apply str (interpose ", " (list (str a " " b) street-address city state)))) 
      ["Test" "Testerson"] test-address))

So they are taking the vector argument and destructuring it in the argument list itself. And destructuring the map right after it, making two arguments into five. Viebel has a few interesting ways to destructure that I did not know about.

I might replace my answers with the provided answers. Now when I run it, lein takes a relatively long time to get through koan 15.

You’re welcome.

There are 224 words in this article.