Tutorial by Examples

Here's how you can destructure a vector: (def my-vec [1 2 3]) Then, for example within a let block, you can extract values from the vector very succinctly as follows: (let [[x y] my-vec] (println "first element:" x ", second element: " y)) ;; first element: 1 , second ele...
Here's how you can destructure a map: (def my-map {:a 1 :b 2 :c 3}) Then, for example, within a let block you can extract values from the map very succinctly as follows: (let [{x :a y :c} my-map] (println ":a val:" x ", :c val: " y)) ;; :a val: 1 , :c val: 3 Notice th...
Let's say you have a vector like so: (def my-vec [1 2 3 4 5 6]) And you want to extract the first 3 elements and get the remaining elements as a sequence. This can be done as follows: (let [[x y z & remaining] my-vec] (println "first:" x ", second:" y "third:&quot...
You can destructure nested vectors: (def my-vec [[1 2] [3 4]]) (let [[[a b][c d]] my-vec] (println a b c d)) ;; 1 2 3 4
Sometimes you want to destructure key under a map which might not be present in the map, but you want a default value for the destructured value. You can do that this way: (def my-map {:a 3 :b 4}) (let [{a :a b :b :keys [c d] :or {a 1 c 2}} my-map] (println ...
Destructurling works in many places, as well as in the param list of an fn: (defn my-func [[_ a b]] (+ a b)) (my-func [1 2 3]) ;= 5 (my-func (range 5)) ;= 3 Destructuring also works for the & rest construct in the param list: (defn my-func2 [& [_ a b]] (+ a b)) (my-func2 1 ...
Destructuring also gives you the ability to interpret a sequence as a map: (def my-vec [:a 1 :b 2]) (def my-lst '("smthg else" :c 3 :d 4)) (let [[& {:keys [a b]}] my-vec [s & {:keys [c d]} my-lst] (+ a b c d)) ;= 10 It is useful for defining functions with named p...
Destructuring allows you to extract data from various objects into distinct variables. In each example below, each variable is assigned to its own string (a="a", b="b", &c.) TypeExampleValue of data / commentvec(let [[a b c] data ...)["a" "b" "c&quot...
Sometimes when destructuring maps, you would like to bind the destructured values to their respective key name. Depending on the granularity of the data structure, using the standard destructuring scheme may be a little bit verbose. Let's say, we have a map based record like so : (def john {:lastn...
(defn print-some-items [[a b :as xs]] (println a) (println b) (println xs)) (print-some-items [2 3]) This example prints the output 2 3 [2 3] The argument is destructured and the items 2 and 3 are assigned to the symbols a and b. The original argument, the entire vector [2 ...

Page 1 of 1