1

我遇到了这个问题......我有两个看起来非常相似的宏

(import java.lang.management.ManagementFactory)

(defmacro with-thread-manager [tm & body]
  {:pre [(and (vector? tm) (= 1 (count tm)))]}
  `(let [~(first tm) (ManagementFactory/getThreadMXBean)]
     ~@body))

(defmacro with-os-manager [tm & body]
  {:pre [(and (vector? tm) (= 1 (count tm)))]}
  `(let [~(first tm) (ManagementFactory/getOperatingSystemMXBean)]
     ~@body))

它们的用法如下:

(defn thread-count []
  (with-thread-manager [tm] (.getThreadCount tm)))

(thread-count)
;; => 12

(defn application-cpu-time []
  (with-os-manager [osm] (.getProcessCpuTime osm)))

(application-cpu-time)
;; => 71260000000

我希望将两者概括with-*-manager为另一个宏,以便可以像这样简化它们:

(defmanagementblock with-thread-manager (ManagementFactory/getThreadMXBean))
(defmanagementblock with-os-manager (ManagementFactory/getOperatingSystemMXBean))

所以我知道的最简单的方法是稍微改变一下宏

(defmacro with-thread-manager [tm & body]
  {:pre [(and (vector? tm) (= 1 (count tm)))]}
  (apply list 'let [(first tm) '(ManagementFactory/getThreadMXBean)]
      body))

并编写块:

(defmacro defmanageblock [name MANAGER]
  (list 'defmacro name '[tm & body]
    '{:pre [(and (vector? tm) (= 1 (count tm)))]}
    (list 'apply 'list ''let (vector '(first tm) 'MANAGER)
          'body)))

一切顺利,除了经理没有正确报价。我尝试了一堆引用和取消引用选项',例如 `~'以及它的许多其他变体。但它没有给出正确的值。

4

2 回答 2

5

如果您将 defmanageblock 定义为一个函数,该函数接受一个描述要使用的工厂的符号,该符号将 s 表达式作为列表返回,那么您将有两个调用函数而不是嵌套宏的宏。在大多数情况下,在函数而不是宏中进行真正的代码生成工作会使代码更容易推理和测试

于 2012-09-13T03:07:23.833 回答
5

一种合理的解决方案,如果您不介意在脑海中跟踪一些范围:

(defmacro defmanagedblock [name mgr]
  `(defmacro ~name [tm# & body#]
     {:pre [(and (vector? tm#)) (= 1 (count tm#))]}
     `(let [~(first tm#) ~'~mgr]
        ~@body#)))
于 2012-09-13T03:55:53.633 回答