Assuming:
(def v [{:a 1} {:a 2} {:a 3}])
(map f v)Exercises:
- write an
fwhich will add one to the value of each:a.
[{:a 2} {:a 3} {:a 4}] - write an
fwhich will:- add one to
:a - add a
:bkey which has a value of 1
[{:a 2 :b 1} {:a 3 :b 1} {:a 4 :b 1}]` - add one to
- write an
fwhich will- add one to
:a - add a
:bkey which has the original value of:a
[{:a 2 :b 1} {:a 3 :b 2} {:a 4 :b 3}] - add one to
- write an
fwhich will- add one to
:a - add a
:bkey which has the original value of:abut only if:ais greater than 3
[{:a 2} {:a 3} {:a 4 :b 3}] - add one to
Possible solutions supplied below - scroll down when you have given it a try ...
Hey, don't cheat. I can see you. Try before you look.
Write an f which will add one to the value of each :a.
[{:a 2} {:a 3} {:a 4}](defn f
[m]
(update m :a inc))
*solution for #2 further below *
Write an f which will:
- add one to
:a - add a
:bkey which has a value of 1
[{:a 2 :b 1} {:a 3 :b 1} {:a 4 :b 1}](defn f
[m]
(let [new-m (update m :a inc)]
(assoc new-m :b 1))or
a very functional approach
(defn f
[m]
(assoc (update m :a inc) :b 1))or
This is more typical clojure code, which uses the threding macro -> (which is effectively the same as the solution above)
(defn f
[m]
(-> m
(update :a inc)
(assoc :b 1)))
Stop cheating!!! Solution for #3 further below
Write an f which will:
- add one to
:a - add a
:bkey which has the original value of :a
[{:a 2 :b 1} {:a 3 :b 2} {:a 4 :b 3}](defn f
[m]
(let [original-a (:a m)]
(-> m
(update :a inc)
(assoc :b original-a))))
Write an f which will:
- add one to
:a - add a
:bkey which has the original value of:abut only if:ais greater than 3
[{:a 2} {:a 3} {:a 4 :b 3}](defn f
[m]
(let [original-a (:a m)
new-m (update m :a inc)]
(if (> original-a 2)
(assoc new-m :b original-a)
new-m)))