出于其他任何事情的好奇(但期望它偶尔可能成为性能调整的有用技巧),是否可以使用 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)}
。因此,虽然这不完全是您所要求的,但您可以使用新的元数据重新绑定 var 以获得内联行为。