英文:
Apply a key as a function to its value
问题
假设你有一张特殊的地图,其中每个键可能代表一个Clojure核心函数:
{:inc 1 :dec 2 :identity "three"}
你想要写什么来将每个键(作为函数)应用于它自己的值?
输出应该得到类似这样的结果:
(2 1 "three")
这段代码未能产生我期望的结果:
user=> (def mm {:inc 1 :dec 2 :identity "three"})
user=> (map #((symbol (first %)) (get % 1)) mm)
(nil nil nil)
英文:
Suppose you have a peculiar map where each key might represent a Clojure core function:
{:inc 1 :dec 2 :identity "three"}
What would you write to apply each key (as a function) to its own value?
Output should yield something like:
(2 1 "three")
This code fails to produce what I expect:
user=> (def mm {:inc 1 :dec 2 :identity "three"})
user=> (map #((symbol (first %)) (get % 1)) mm)
(nil nil nil)
答案1
得分: 1
用 resolve
将符号包装起来可以解决这个问题:
(resolve (symbol (...)))
更详细的解释请查看这里:https://stackoverflow.com/a/63208807/4903731
以下任何一种方式都会产生所需的输出:
(def mm {:inc 1 :dec 2 :identity "three"})
(map (fn [%] ((resolve (symbol (key %))) (val %))) mm)
(map #((resolve (symbol (key %))) (val %)) mm)
(map #((resolve (symbol (first %))) (get % 1)) mm)
英文:
Wrapping the symbol with resolve
solves this problem:
(resolve (symbol (...)))
More detailed explanation here: https://stackoverflow.com/a/63208807/4903731
Any of the following produce the desired output:
(def mm {:inc 1 :dec 2 :identity "three"})
(map (fn [%] ((resolve (symbol (key %))) (val %))) mm)
(map #((resolve (symbol (key %))) (val %)) mm)
(map #((resolve (symbol (first %))) (get % 1)) mm)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论