clojure-koans/src/koans/destructuring.clj

43 lines
1.3 KiB
Clojure
Raw Normal View History

2010-11-12 00:16:55 +00:00
(def test-address
{:street-address "123 Test Lane"
:city "Testerville"
:state "TX"})
2010-11-06 22:38:31 +00:00
(meditations
"Destructuring is an arbiter: it breaks up arguments"
2010-11-06 22:38:31 +00:00
(= __ ((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"]]
__))
2010-11-12 00:16:55 +00:00
"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))
)