I wanna get the string representation of a variable. For example,
(def my-var {})
How to get the string "my-var"
from symbol my-var
? And
(defn my-fun [] ...)
How to get the string "my-fun"
from function my-fun
?
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
Every Var in Clojure has :name metadata attached.
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, usually if you already have the Var, then you already know the name anyway, and usually you don't use Vars in a program (i.e., you just pass my-var or my-fun rather than #'my-var and #'my-fun).
There's nothing to get the Var (or var-name) of a function or a value that happens to be the value of some Var. A Var knows its value, but not the other way round. That of course makes sense since, e.g., the very same function may be the value of zero (for local functions) or multiple vars.
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"
Doesn't work for function or macro names though, 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With