如何在 REPL 的 Clojure 中显示函数的定义? [英] How can I display the definition of a function in Clojure at the REPL?
问题描述
我正在寻找让 REPL 打印函数的当前定义的能力.有没有办法做到这一点?
I'm looking for the ability to have the REPL print the current definition of a function. Is there any way to do this?
例如,给定:
(defn foo [] (if true "true"))
我想说类似的话
(print-definition foo)
并得到一些类似
(foo [] (if true "true"))
印刷.
推荐答案
source
的替代方案(启动 REPL 时应通过 clojure.repl/source
获得),从 1.2.0
开始.如果您使用的是 1.1.0
或更低版本,source
在 clojure.contrib 中.repl-utils
.),用于 REPL,而不是查看 .clj
文件中定义的函数:
An alternative to source
(which should be available via clojure.repl/source
when starting a REPL, as of 1.2.0
. If you're working with 1.1.0
or lower, source
is in clojure.contrib.repl-utils
.), for REPL use, instead of looking at functions defined in a .clj
file:
(defmacro defsource
"Similar to clojure.core/defn, but saves the function's definition in the var's
:source meta-data."
{:arglists (:arglists (meta (var defn)))}
[fn-name & defn-stuff]
`(do (defn ~fn-name ~@defn-stuff)
(alter-meta! (var ~fn-name) assoc :source (quote ~&form))
(var ~fn-name)))
(defsource foo [a b] (+ a b))
(:source (meta #'foo))
;; => (defsource foo [a b] (+ a b))
一个简单的打印定义
:
(defn print-definition [v]
(:source (meta v)))
(print-definition #'foo)
#'
只是一个 reader 宏,从 #' 扩展而来foo
到 (var foo)
:
#'
is just a reader macro, expanding from #'foo
to (var foo)
:
(macroexpand '#'reduce)
;; => (var reduce)
这篇关于如何在 REPL 的 Clojure 中显示函数的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!