通过将字符串转换为符号来提取 Atom 中键的值

Extracting Value of Key in Atom by Converting String to Symbol

我有一个原子:

{:answer1 "yes", :answer2 "no", :answer3 "maybe"}

并且我希望能够使用变量 x 来提取 :answerx 的值。

在我的 REPL 中,当我测试如何附加到字符串然后转换为符号时,这有效:

(symbol (str ":answer" 2))

结果是:answer2。但是,当我尝试在原子内执行此操作时,我得到的结果为 nil:

(get @answers-atom (symbol (str ":answer" 2)))

知道为什么会这样吗?

您似乎混淆了符号和关键字。例如,在您在问题开头给出的地图中,:answer1:answer2:answer3 是关键字,但 (symbol (str ":answer" 2)) 是符号。要获取关键字,您需要改为使用 keyword 函数:

(def m {:answer1 "yes" :answer2 "no" :answer3 "maybe"})

(get m (symbol (str ":answer" 2))) ;=> nil

(get m (keyword (str "answer" 2))) ;=> "no"