如何在Clojure中以字符串形式获取函数名称? [英] How to get function's name as string in Clojure?

查看:51
本文介绍了如何在Clojure中以字符串形式获取函数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Clojure中以字符串的形式获取函数名称?

How can you get function's name as string in Clojure?

到目前为止,我所学到的东西似乎都不是惯用的:

What I have so far doesn't look anywhere near idiomatic:

(defn fn-name
  [f]
  (first (re-find #"(?<=\$)([^@]+)(?=@)" (str f))))

(defn foo [])

(fn-name foo) ;; returns "foo"

编辑:根据提供的提示,我将我想要的基本宏。看起来好些吗?

With the provided hints I put together a basic macro that does what I want. Does it look better?

(defmacro fn-name
  [f]
  `(-> ~f var meta :name str))


推荐答案

对于函数使用 defn 形式定义:

For functions defined with the defn form:

user> (-> #'map meta :name)
map
user> (defn nothing [& _])
#'user/nothing
user> (-> #'nothing meta :name)
nothing

这需要访问var,而不仅仅是var保留的函数值。

This requires access to the var, rather than just the function value the var holds.

这篇关于如何在Clojure中以字符串形式获取函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆