将一个键应用为其值的函数。

huangapple go评论49阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年2月19日 12:26:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定