无法解决符号:在此上下文中的新图

发布于 2025-02-03 18:21:56 字数 868 浏览 2 评论 0原文

我正在搜索,无法找到我问题的答案。

我正在阅读勇敢和真实的clojure地图上的地图值。

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

它可以正常工作,除了它在repl和文件中丢弃了错误:

java.lang.exception:无法解析符号:在此上下文中的新映射

java.lang.exception:在此上下文中执行函数内部执行时

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

:我自己的实现(阅读第三章后)效果很好:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲影 2025-02-10 18:21:56

问题在于,我已经用一个参数遮盖了fn。新映射不再是匿名函数中的参数,并且Clojure试图将其评估为传递给函数fn的向量中的值。

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

愚蠢的错误,我要添加这个答案,以防万一有人会有相同的错误,而我已经花了一些时间来创建一个问题。

这是第一步,您可以看到我尚未用FN替换的原始代码中有inc,因为即使在repl中也存在编译器错误。

另外,问题在于,我的第一个实现map-map没有使用fn宏,因此我可以将其用作函数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文