clojure生成一个向量vs一个map文字表达式

时间:2015-08-18 17:08:29

标签: 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)]) 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}

怎么回事?

2 个答案:

答案 0 :(得分:2)

该异常由读者触发,因为在评估之前,它无法读取带有一个元素的文字地图。

解决方法:

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

答案 1 :(得分:0)

除非您正在撰写宏,否则最简单的说法是:

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