Clojure宏为函数创建同义词 [英] Clojure macro to create a synonym for a function

查看:122
本文介绍了Clojure宏为函数创建同义词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任何真正知道如何在任何Lisp中编写宏的人来说,这很容易。我想要能够定义函数名的同义词。我已经复制和粘贴黑客core.clj做到这一点,但我不想永远是这样的笨蛋!看起来很明显,一个宏将重写对synoym函数的调用转换为对原始函数的调用是正确的方法。

Probably an easy one for anyone who actually knows how to write macros in any Lisp. I want to be able to define synonyms for function names. I've been copy-and-paste hacking core.clj to do this, but I don't want to be such a dunce forever! It seems obvious a macro that rewrites the call to a synoym-function into a call to the original function is the right way to do it.

推荐答案

如果我理解你的问题,有一个更简单的方法:将新符号替换为旧函数。

If I understand your question, there's an easier way: def the new symbol to the old function.

user=> (def foo +)
#'user/foo 
user=> (foo 1 2) 
3






def的性能也胜过宏观方法:


The performance of def also outperforms the macro approach:

(defmacro foo2 [& args]
  `(+ ~@args))

foo2实际上是+的别名,行为方式完全相同

foo2 is then effectively an alias for + and behaves exactly the same way (being rewritten as +) except for the restrictions that are placed on using macros where a value must be returned.

如果你希望别名的行为是完全一样的作为原始函数(在相同的上下文中也可调用),那么你需要使用def重命名函数。

If you want the behavior of the "alias" to be exactly the same as that of the original function (callable in the same contexts as well) then you need to use def to rename the function.

user=> (def foo +)

user=> (defn foo1 [& args]
         `(+ ~@args))

user=> (defmacro foo2 [& args]
         `(+ ~@args))

user=> (time (dotimes [n 1000000] (foo 1 n)))
"Elapsed time: 37.317 msecs"

user=> (time (dotimes [n 1000000] (foo1 1 n)))
"Elapsed time: 292.767 msecs"

user=> (time (dotimes [n 1000000] (foo2 1 n)))
"Elapsed time: 46.921 msecs"

这篇关于Clojure宏为函数创建同义词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆