rake-write-code
rake-write-code

Reputation: 43

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

Upvotes: 0

Views: 107

Answers (3)

Brandon Henry
Brandon Henry

Reputation: 3720

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)))

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295443

(def items {:my-item {:item-count 10}})
(update-in items [:my-item :item-count] #(- % 3))

Upvotes: 0

amalloy
amalloy

Reputation: 91907

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

Upvotes: 3

Related Questions