Clojure macro to create a synonym for a function

后端 未结 2 511
后悔当初
后悔当初 2021-01-18 09:57

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 hack

2条回答
  •  长发绾君心
    2021-01-18 10:08

    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
    

    The performance of def also outperforms the macro approach:

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

    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.

    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"
    

提交回复
热议问题