Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 637
qiuxiafei Avatar asked Jun 14 '12 09:06

qiuxiafei


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
like image 93
number23_cn Avatar answered Oct 22 '22 12:10

number23_cn


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.

like image 38
Tassilo Horn Avatar answered Oct 22 '22 10:10

Tassilo Horn


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)
like image 33
stand Avatar answered Oct 22 '22 10:10

stand