更多的是出于对其他任何东西的好奇(但期望它可能偶尔会成为性能调优的有用技巧),是否可以使用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)))
答案 0 :(得分:14)
如果您不知道,可以使用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以获得内联行为。