clojure 生成向量与地图文字表达式

clojure generating a vector vs a map literal expression

这似乎很矛盾:

(def foo ["some" "list" "of" "strings"])

`[ ~@(apply concat (map (fn [a] [a (symbol a)]) foo)) ]
; ["some" some "list" list "of" of "strings" strings]

; Changing only the outer [] into {} 
`{ ~@(apply concat (map (fn [a] [a (symbol a)]) foo)) }
; RuntimeException Map literal must contain an even number of forms

; However, this works:
`{"some" some "list" list "of" of "strings" strings}
; {"list" clojure.core/list, "of" user/of, "strings" user/strings, "some" clojure.core/some}

怎么回事?

异常是由reader触发的,因为它无法读取包含一个元素的文字映射,该元素是您在评估之前的未拼接形式。

解决方法:

`{~@(apply concat (map (fn [a] [a (symbol a)]) foo)) ~@[]} 

除非你正在编写宏,否则最简单的说法可能是:

(into {} (map (fn [a] [a (symbol a)]) foo))
;=> {"some" some, "list" list, "of" of, "strings" strings}