Created
June 9, 2020 20:12
-
-
Save Reefersleep/b486cb428d2537faa3f6eb571b2b065a to your computer and use it in GitHub Desktop.
Nested destructuring in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(let [person {:first-name "Fred" ;;Binding this map literal, with stuff nested in it, to the symbol 'person'. | |
:age 42 | |
:pets {:dogs ["Rusty" "Fido"] | |
:cats ["Snowy" "Tom" "Garfield" "Queenie"]} | |
:family [{:name "Sarah" | |
:relation :wife} | |
{:name "Dennis" | |
:relation :son}]} | |
;;Here comes a bunch of destructuring! | |
{:keys [first-name age] ;;Just picking key values directly from the root level of the map | |
{[first-dog second-dog] :dogs ;;Taking the vector keyed by :dogs (inside the :pets map) and binding the first two values in the vector to symbols. | |
[first-cat & rest-cats] :cats} :pets ;;More of the same | |
[{:keys [name relation] :as family-1} family-2] :family} person] ;;Destructuring family. | |
;;Using the destructured values | |
(str "The person is called " first-name " and is " age " years old. \n" | |
"He has 2 dogs, " first-dog " and " second-dog ". \n" | |
"He has a bunch of cats, " first-cat ", as well as the rest in this list: " rest-cats ". \n" | |
"He has two relations, represented by maps in a vector keyed by :family. \n" | |
family-1 " is his " relation " and is called " name ". \n" | |
family-2 " is... something else that I didn't destructure.")) | |
=> | |
"The person is called Fred and is 42 years old. | |
He has 2 dogs, Rusty and Fido. | |
He has a bunch of cats, Snowy, as well as the rest in this list: (\"Tom\" \"Garfield\" \"Queenie\"). | |
He has two relations, represented by maps in a vector keyed by :family. | |
{:name \"Sarah\", :relation :wife} is his :wife and is called Sarah. | |
{:name \"Dennis\", :relation :son} is... something else that I didn't destructure." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment