Skip to content

Instantly share code, notes, and snippets.

@mike-thompson-day8
Last active March 31, 2020 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike-thompson-day8/5afd782e48d308b8e6015ff88767fa9d to your computer and use it in GitHub Desktop.
Save mike-thompson-day8/5afd782e48d308b8e6015ff88767fa9d to your computer and use it in GitHub Desktop.

Some Exercises And Solutions For Beginners

Assuming:

(def  v [{:a 1} {:a 2} {:a 3}])
  
(map f v)

Exercises:

  1. write an f which will add one to the value of each :a.
    [{:a 2} {:a 3} {:a 4}]
  2. write an f which will:
    • add one to :a
    • add a :b key which has a value of 1
     [{:a 2 :b 1} {:a 3 :b 1} {:a 4 :b 1}]`
  3. write an f which will
    • add one to :a
    • add a :b key which has the original value of :a
    [{:a 2 :b 1} {:a 3 :b 2} {:a 4 :b 3}]
  4. write an f which will
    • add one to :a
    • add a :b key which has the original value of :a but only if :a is greater than 3
    [{:a 2} {:a 3} {:a 4 :b 3}]





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.








Solution for #1

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 *















Solution for #2

Write an f which will:

  • add one to :a
  • add a :b key 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















Solution for #3

Write an f which will:

  • add one to :a
  • add a :b key 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))))















Solution for #4

Write an f which will:

  • add one to :a
  • add a :b key which has the original value of :a but only if :a is 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)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment