In Clojure, how to get a name string from a variable or function?

I want to get a string representation of a variable. For instance,

(def my-var {}) 

How to get the string "my-var" from the my-var character? AND

 (defn my-fun [] ...) 

How to get the string "my-fun" from my-fun function?

+6
source share
3 answers
 user=> (def my-var {}) #'user/my-var user=> (defn my-fun [] ) #'user/my-fun user=> (name 'my-var) "my-var" user=> (name 'my-fun) "my-fun" user=> (doc name) ------------------------- clojure.core/name ([x]) Returns the name String of a string, symbol or keyword. nil 
+12
source

Each Var in Clojure has: name metadata.

 user> (def my-var {}) #'user/my-var user> (:name (meta #'my-var)) my-var user> (let [a-var #'my-var] (:name (meta a-var))) my-var 

However, as a rule, if you already have Var, then you already know the name anyway, and usually you do not use Vars in the program (i.e. you just pass my-var or my-fun, not # -var and # 'my-fun).

There is nothing to get a Var (or var-name) function or value that turns out to be the value of some Var. Var knows its value, but not vice versa. This, of course, makes sense, because, for example, the function itself can be a value of zero (for local functions) or several vars.

+7
source

How about this?

 (defn symbol-as-string [sym] (str (second `(name ~sym))) => (def my-var {}) #'user/my-var => (symbol-as-string my-var) "my-var" => (symbol-as-string 'howdy) "howdy" 

Not working for function name or macro, maybe someone can help me

 => (symbol-as-string map) " clojure.core$map@152643 " => (symbol-as-string defn) java.lang.Exception: Can't take value of a macro: #'clojure.core/defn (NO_SOURCE_FILE:31) 
+1
source

Source: https://habr.com/ru/post/918071/


All Articles