开发者

Redefining "def" in Clojure

Is there anyway to define a new macro under the name开发者_StackOverflow社区 def in Clojure? I defmacroed a new one after trying to :refer-clojure :exclude the original, but it used the built-in definition anyway.

I was trying to enable Scheme-style function definitions ((def (f x y) ...) as (defn f [x y] ...)) using the following code.

(defmacro def
  [ id & others ]
    (if (list? id)
        `(defn ~(first id) [~@(rest id)] ~@others)
        `(def ~id ~@others)))


def is not a macro, it is a special form. It interns a symbol into current namespace. You cannot redefine special forms, but even if you could, how would you get same behavior?

The most straightforward way is to write define macro on base of def and defn. If you want to use def word, you can write a wrapper replace-my-def-with-normal-def around all the module, i.e.

(replace-my-def-with-normal-def

   (def x 0)
   (def y (inc x))
   (def z (inc y))
   (def (my-func a b) (println a b))

)

but I'm not sure it won't break other definitions, which depend on def (for example, defn).


You can create a macro with the name of a special form (like if), but it won't help you. Special forms are evaluated before macros, therefore if you have a macro and a special form of same name the special form will always be used. More information here http://clojure.org/evaluation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜