【问题标题】:clojure generating a vector vs a map literal expressionclojure 生成向量与地图文字表达式
【发布时间】:2015-08-18 17:08:29
【问题描述】:

这似乎很矛盾:

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

怎么了?

【问题讨论】:

    标签: clojure macros


    【解决方案1】:

    异常由阅读器触发,因为它无法读取具有一个元素的文字映射,该元素是评估之前的未拼接形式。

    解决方法:

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

    【讨论】:

      【解决方案2】:

      除非您正在编写宏,否则可能最容易说:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-26
        • 2019-12-22
        相关资源
        最近更新 更多