Search code examples
clojure

Using update-in without a get-in to retrieve the value to modify


I am new to Clojure and I'm trying to update a map using the update-in and anonymous functions

(def items {:my-item {:item-count 10}})

(update-in items [:my-item :item-count]
           (fn [%] (- (get-in items [:my-item :item-count])  3)))

The expected results are that the item count should be now 7, my code works but I'm wondering if I can do this without calling the get-in method.

Another approach I tried is below:

(update-in items [:my-item :item-count]
           (dec (fn [%] 3)))

Which gives me

cannot be cast to java.lang.Number

Solution

  • your anonymous function should take the thing it wants to modify and use that instead of doing the get-in

    (update-in items [:my-item :item-count]
           (fn [item-count] (- item-count 3)))