Slide 1

Slide 1 text

Destructuring Friday, October 11, 13

Slide 2

Slide 2 text

Apart from simple types, there are collections, which contain other things. Friday, October 11, 13

Slide 3

Slide 3 text

But sometimes we want simple data out of a collection type. Friday, October 11, 13

Slide 4

Slide 4 text

Actually, quite often. Friday, October 11, 13

Slide 5

Slide 5 text

(def my-collection [1 2 [3 4] 5]) (first my-collection) ;=> 1 (nth my-collection 2) ;=> [3 4] Friday, October 11, 13

Slide 6

Slide 6 text

It takes a function(+) and some arguments(1) and returns a closure with the arguments pre-set. But if we want multiple elements, this gets ugly fast: (let [a (nth my-collection 0) b (nth my-collection 1) c (nth my-collection 2) d (nth my-collection 3)] (println a c)) Friday, October 11, 13

Slide 7

Slide 7 text

How many of you know Python? Friday, October 11, 13

Slide 8

Slide 8 text

How many of you know Python? a, b, c, d = my_collection Friday, October 11, 13

Slide 9

Slide 9 text

We want this too! Friday, October 11, 13

Slide 10

Slide 10 text

Hey, we can do this too! (let [[a b c d] my-collection] (println a c)) Friday, October 11, 13

Slide 11

Slide 11 text

What about this? a, b, *more = my_collection Friday, October 11, 13

Slide 12

Slide 12 text

Can do! (let [[a b & more] my-collection] (println a more)) Friday, October 11, 13

Slide 13

Slide 13 text

But wait, it's not only vectors! (def my-map {:lang "Clojure" :platform "JVM" :version "1.5.1"}) (let [{language :lang} my-map] (println language)) Friday, October 11, 13

Slide 14

Slide 14 text

Sothere is some kind of"unpacking language"? Friday, October 11, 13

Slide 15

Slide 15 text

Sothere is some kind of"unpacking language"? YEPa This is called destructuring. Friday, October 11, 13

Slide 16

Slide 16 text

What else? • You can use this language in binding forms • So, not only let but also fn/defn • It works recursively • More hands-on stuff in the exercises Friday, October 11, 13