出于对其他任何事情的好奇(但期望它偶尔会成为性能调整的有用技巧),是否可以使用 Clojure 宏来“内联”现有函数?
即我希望能够执行以下操作:
(defn my-function [a b] (+ a b))
(defn add-3-numbers [a b c]
(inline (my-function
a
(inline (my-function
b
c)))))
并让它(在编译时)产生与我自己内联添加的完全相同的功能,例如:
(defn add-3-numbers [a b c]
(+ a (+ b c)))
最佳答案
如果您不知道,您可以使用 definline
定义内联函数
(doc definline)
-------------------------
clojure.core/definline
([name & decl])
Macro
Experimental - like defmacro, except defines a named function whose
body is the expansion, calls to which may be expanded inline as if
it were a macro. Cannot be used with variadic (&) args.
nil
还要检查来源,
(source definline)
-------------------------
(defmacro definline
[name & decl]
(let [[pre-args [args expr]] (split-with (comp not vector?) decl)]
`(do
(defn ~name ~@pre-args ~args ~(apply (eval (list `fn args expr)) args))
(alter-meta! (var ~name) assoc :inline (fn ~name ~args ~expr))
(var ~name))))
definline
简单定义一个 var
带有元数据 {:inline (fn definition)}
.因此,尽管它不完全符合您的要求,但您可以使用新的元数据重新绑定(bind) var 以获得内联行为。
关于performance - 使用 Clojure 宏内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4477759/