Avoid overriding variable names

In the specific namespace I'm working on, I end up with function names. Is there a way to get a warning similar to the one I get if I redefine a character from another namespace, if I reuse a character that is already associated with a function in the same namespace?

+5
source share
3 answers

If this is enough that you want to replace the (set) of basic macros, you can try this approach:

(ns huge.core
  (:refer-clojure :exclude [defn]))

(defmacro defn [name & defn-tail]
  (assert (nil? (resolve name))
          (str "Attempting to redefine already defined Var "
               "#'" (.name *ns*) "/" name))
  `(clojure.core/defn ~name ~@defn-tail))

Then, any attempt to redefine the existing Var with defnwill fail:

user=> (defn foo [] :foo)
#'user/foo
user=> (defn foo [] :bar)
AssertionError Assert failed: Attempting to redefine already defined Var #'user/foo
(nil? (resolve name))  user/defn (NO_SOURCE_FILE:2)

defmacro; clojure.core/defmacro .

, def , Vars. , defvar ( clojure.contrib.def) .

+4

, , . letfn, , .

(defn main-fn [x]
  (letfn [(secondary-fn [x] (* x x))
          (another-fn [x] (secondary-fn (inc x)))]
    (/ (another-fn x) 4)))
+2

Even if you limit yourself to the names of single-character functions, you do not run the risk of exhausting yourself, since there are (about) 64 thousand Unicode characters, any of which is a valid function name.

Given that you may have ten thousand characters long names, you are on even more secure ground.

+1
source

All Articles