clojure生成向量与映射文字表达式

clojure生成向量与映射文字表达式,clojure,macros,Clojure,Macros,这似乎自相矛盾: (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)]) fo

这似乎自相矛盾:

(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}

发生了什么?

异常是由读取器触发的,因为它无法读取包含一个元素的文字映射,该元素是求值前的未切片表单

解决方法:

`{~@(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}