Search code examples
clojureclojurescript

Changing value of atom vector using swap


I have

(def data {:headers ["A" "B" "C" "D"]
                 :rows [["1" "2" "3" "4"] ["5" "6" "7" "8"] ["9" "10" "11" "12"]]})

And I have a function

(defn replace-value [struct] 
    (clojure.walk/prewalk-replace {"3" "hello"} (struct :rows)))

When I do

(replace-value @data) > [["1" "2" "hello" "4"] ["5" "6" "7" "8"] ["9" "10" "11" "12"]]

I get what I expect.

However, I want to achieve this same result using swap! So I tried

#(swap! data (replace-value %))

but I get the error #object[user$eval1308$fn__1309 0x6caeefd7 "user$eval1308$fn__1309@6caeefd7"]

I don't know what this error means nor how to resolve it


Solution

  • #(swap! data (replace-value %))
    

    creates an anonymous function with one parameter so it not an error but will not perform the swap until executed. If you try to execute it you will receive an error since swap! expects the first parameter to be an atom rather than a map.

    It looks like you want:

    (def a (atom data))
    (swap! a #(replace-value %))
    

    or simply

    (swap! a replace-value)