Clojure Easy · Lesson 1 · On the house

Destructuring

Vector and map destructuring in let and fn params, :keys, :or and :as. Lesson 1 is free — on the house.

Lessons · Clojure Easy · Lesson 1 of 10 · On the house

Destructuring

Vector and map destructuring in let and fn params, :keys, :or and :as.

Illustration for Clojure
Lesson 1 is on the house.

Vector destructuring binds by position: (let [[a b & more] [1 2 3 4]] ...) gives a 1, b 2 and more (3 4). Use _ for values you skip.

Map destructuring binds by key: {:keys [name age]} pulls :name and :age into locals of the same names. :strs and :syms do the same for string and symbol keys.

:or {age 0} supplies defaults for missing keys, and :as user keeps the whole value too.

It works in function parameters: (defn greet [{:keys [name]}] (str "hi " name)), which is how Clojure takes named options.

Nested forms destructure nested data: [{[x y] :pos}] reaches into a map's vector.

destructuring

(let [[a b & more] [1 2 3 4]]
  (println a b more))

(defn describe [{:keys [name age] :or {age 0} :as user}]
  (str name " is " age ", keys " (count user)))

(println (describe {:name "Ada" :age 36}))
(println (describe {:name "Bo"}))

(let [{[x y] :pos} {:pos [3 4]}]
  (println (+ x y)))
Match this when you type.

Quiz

What is more in [[a b & more] [1 2 3 4]]?

Quiz

What does {:keys [name]} do?

Quiz

What does (describe {:name "Bo"}) return?

Quiz

What does :as user bind?

Check

Match the still for: Destructuring.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.