Skip to content

Instantly share code, notes, and snippets.

@sudowork
Last active December 15, 2015 17:09
Show Gist options
  • Save sudowork/5294502 to your computer and use it in GitHub Desktop.
Save sudowork/5294502 to your computer and use it in GitHub Desktop.
; First let's show two alternative ways to destructure a vector
user=> (defn first-three [a & [b & [c]]] (println a b c))
#'user/first-three
user=> (defn first-three [a b c & _] (println a b c))
#'user/first-three
user=> (first-three 1 2 3 4)
1 2 3
nil
user=> (first-three 1 2)
1 2 nil
nil
; Let's destructure a tic-tac-toe board
user=> (def board [[:x :o :x] [:o :x :o] [:x :o :x]])
#'user/board
user=> (defn center "Get center mark" [[_ [_ c _] _]] c)
#'user/center
user=> (defn center "Get center mark" [[_ [_ c]]] c) ; we don't need to specify the entire structure
#'user/center
user=> (center board)
:x
; But wait, the documentation is ugly and hard to understand
; Let's hide the destructuring using let to create a local lexical scope
user=> (doc center)
-------------------------
user/center
([[_ [_ c]]])
Get center mark
nil
user=> (defn center "Get center mark" [board]
#_=> (let [[_ [_ c]] board] c))
#'user/center
user=> (doc center)
-------------------------
user/center
([board])
Get center mark
nil
; We can even destructure maps within vectors!
user=> (defn print-profs [profs]
#_=> (let [[{prof1 :name} {prof2 :name}] profs]
#_=> (printf "Professors: %s and %s\n" prof1 prof2)))
#'user/print-profs
user=> (print-profs [{:name "Kevin", :editor "vim"} {:name "Yang", :editor "sublime"}])
Professors: Kevin and Yang
nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment