Created
October 18, 2012 19:48
-
-
Save sids/3914384 to your computer and use it in GitHub Desktop.
Clojure Destructuring examples
This file contains 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
;;; This is taken from http://paste.lisp.org/display/97057 | |
;;; (which is no more; thanks to Wayback Machine which let me retrieve this). | |
;;; http://clojure.googlegroups.com/web/tutorial.pdf | |
;;; Vector binding forms destructure sequential things (vectors, | |
;;; lists, seqs, strings, arrays, and anything that supports nth) | |
;;; Map binding forms destructure associative things (maps, vectors, strings and arrays; | |
;;; the latter three have integer keys) | |
user> (let [[a b c] "xyz"] | |
[a b c]) | |
[\x \y \z] | |
user> (let [[a b c & d :as e] [1 2 3 4 5 6 7]] | |
[a b c d e]) | |
[1 2 3 (4 5 6 7) [1 2 3 4 5 6 7]] | |
user> (let [{a :a b :b c :c :as m :or {a 2 b 3}} {:a 5 :c 6}] | |
[a b c m]) | |
[5 3 6 {:a 5, :c 6}] | |
user> (let [{:keys [a b c] :as m :or {a 2 b 3}} {:a 5 :c 6}] | |
[a b c m]) | |
[5 3 6 {:a 5, :c 6}] | |
user> (let [{:strs [a b c] :as m :or {a 2 b 3}} {"a" 5 "c" 6}] | |
[a b c m]) | |
[5 3 6 {"a" 5, "c" 6}] | |
user> (let [{a 0 b 3 :as c} [12 34 56 78 90]] | |
[a b c]) | |
[12 78 [12 34 56 78 90]] | |
user> (let [{a 100} (vec (take 500 (iterate #(+ % 2) 0)))] | |
a) | |
200 | |
user> (let [[{a :a b :b c :c :as m :or {a 100 b 200}} | |
[p q r & s]] | |
[{:a 5 :c 6} | |
[1 2 3 4 5]]] | |
[a b c m | |
p q r s]) | |
[5 200 6 {:a 5, :c 6} 1 2 3 (4 5)] | |
user> (let [[{:keys [a b c]} | |
& [[d & e] | |
{:keys [x y] :or {z 10000 y 555}}]] | |
[{:a 1 :b 2} | |
"quux" | |
{:x 1000 :y 999}]] | |
[a b c d e x y]) | |
[1 2 nil \q (\u \u \x) 1000 999] | |
user> (let [[a & [b & c]] | |
(range 0 5)] | |
[a b c]) | |
[0 1 (2 3 4)] | |
user> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment