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

ε祈祈猫儿з 提交于 2020-01-02 02:37:15

问题


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?


回答1:


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



回答2:


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.




回答3:


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)


来源:https://stackoverflow.com/questions/11030107/in-clojure-how-to-get-the-name-string-from-a-variable-or-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!