Destructuring






cycognito



clojure logo

Topics

An elegant syntactic sugar

Destructuring a sequence

Destructuring the first 2 values

(let [[x y] [5 7]]
  {:x x
   :y y})

Skip some items with _

(let [[x _ _ y] [5 6 8 7]]
  {:x x
   :y y})

Split a vector into first and rest

(let [[x & more] [1 2 3]]
  {:x x :more more})

Keep access to the whole sequence

(let [[x & more
       :as full-list] (range 3)]
  {:x x
   :more more
   :full-list full-list})

Destructuring a map

Choose local names and provide keys

(let [{the-x :x the-y :y} {:x 5 :y 7}]
  (+ the-x  the-y))

Most useful piece of destructuring

(let [{:keys [x y]} {:x 5 :y 7}]
  (+ x y))

Keep access to the whole map

(let [{:keys [x y] :as p} {:x 5 :y 7}]
  p)

Practice

Can you guess how to destructure a map that is inside a vector?

For example [{:a 1 :b 2}]?

Solution

(let [[{:keys [a b]}] [{:a 1 :b 2}]]
  a)

Practice

Write a function foo that receives a map with 3 keys :a, :b and :c and returns the greatest value in the map, where:

  1. :a and :b are required

  2. :c is optional with a default value of 10

(defn foo [])