【问题标题】:Using Sequences in clojure macros在 clojure 宏中使用序列
【发布时间】:2014-11-12 20:50:53
【问题描述】:

我正在从 yaml 文件中读取数据,结果如下:

{:test1 (1 2 3)}

我可以查找键 :test1 并获得带有元素 1 2 3clojure.lang.LazySeq。但是当我想在宏中使用这些数据时,它会扩展为函数调用而不是引用列表。

例如:

(defmacro mmerge
  [map1 map2]
  `(assoc ~(merge map1 map2) :merged true))

(mmerge {:test1 (1 2 3)} {:test2 (4 5 6)})

这被扩展为:

(clojure.core/assoc {:test2 (4 5 6), :test1 (1 2 3)} :merged true)

是否有可能以某种方式使其工作?

提前致谢

【问题讨论】:

  • 为什么这是一个宏?

标签: macros clojure


【解决方案1】:

如果您将映射参数的值写为带引号的列表,您可以使用函数实现相同的目的:

(defn mmerge*
  [map1 map2]
  (assoc (merge map1 map2) :merged true))

(mmerge* {:test1 '(1 2 3)} {:test2 '(4 5 6)})
;= {:merged true, :test2 (4 5 6), :test1 (1 2 3)}

如果你仍然想要一个宏,你需要以宏返回的形式引用merge操作的结果(或者@fl00r mentioned,如果你只引用列表是绝对正确的:P):

(defmacro mmerge
  [map1 map2]
  `(assoc '~(merge map1 map2) :merged true))

这会导致以下宏展开:

(clojure.core/assoc '{:test2 (4 5 6), :test1 (1 2 3)} :merged true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2011-07-24
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多