Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Clojure Destructuring Examples
;; Anything you type in here will be executed
;; immediately with the results shown on the
;; right.
(def name ["Tom" "David" "Crinson"])
(str (nth name 2) ", "
(nth name 0) " "
(nth name 1))
;=> "Crinson, Tom David"
;;; VS
(let [[fname mname lname] name]
(str lname ", " fname " " mname ))
; => "Crinson, Tom David"
;; Slurp Remainder
(def very-posh-person ["Geoffery" "Van" "Winkle" "The" "Third"])
(let [[fname mname lname & more] very-posh-person]
(str lname ", " fname " " mname " " more))
;=> "Winkle, Geoffery Van (\"The\" \"Third\")"
;;; :as
(let [[fname mname lname :as whole] name]
(str lname ", " fname " " mname " (" whole ")" ))
; => "Crinson, Tom David ([\"Tom\" \"David\" \"Crinson\"])"
;;; Associative destructuring
(let [{fname 0 lname 2} name]
(str fname " " lname))
;=> "Tom Crinson"
;; Maps
(def mapname {:fname "Tom" :mname "David" :lname "Crinson"})
(let [{fname :fname lname :lname} mapname]
(str fname " " lname))
; => "Tom Crinson"
(let [{:keys [fname lname]} mapname]
(str fname " " lname))
; => "Tom Crinson"
(let [{:keys [fname lname title]} mapname]
title)
; => nil
(def nested-map {:title "Eternal Golden Braid"
:author "Douglas Hofstadter",
:chapters [{:title "Introduction:
A Musico-Logical Offering"}
{:title "Chapter 1:
The MU-puzzle"}]})
(let [{[introduction {ch1_title :title}] :chapters title :title} nested-map]
str ch1_title)
(def funsies "DeAstruRcturSing isE fun!")
(let [{a 2 b 7 c 12 d 19} funsies]
(str a b c d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.