Unable to resolve symbol: new-map in this context in Clojure

Viewed 43

I was searching and was not able to find the answer to my question.

I'm reading Clojure For The Brave and True and found the implementation of the map over map values.

(reduce (fn [new-map [key val]]
          (assoc new-map key (inc val)))
        {}
        {:max 30 :min 10})

which works fine, except it throws an error in both REPL and file:

java.lang.Exception: Unable to resolve symbol: new-map in this context

when executed inside a function:

(defn map-map [fn hash]
  (reduce (fn [new-map [key val]]
            (assoc new-map key (inc val)))
          {}
          hash))

My own implementation (after reading 3rd chapter) works fine:

(defn map-map [fn hash]
  (into {} (map #(conj [(first %)] (fn (second %))) hash)))
1 Answers

The problem is that I've shadowed the fn with an argument. new-map is no longer a parameter in an anonymous function, and Clojure tries to evaluate it as the value in a vector that is passed to function fn.

(defn map-map [func hash]
  (reduce (fn [new-map [key val]]
            (assoc new-map key (func val)))
          {}
          hash))

Silly mistake, I'm adding this answer just in case someone will have the same error, and I've already taken the time to create a question.

This was the first step as you can see there is inc in the original code that I didn't yet replace with fn, because of a compiler error even in REPL.

Also, the problem was that my first implementation of map-map didn't use the fn macro so I could use it as a function.

Related