如何在REPL中显示Clojure中函数的定义? [英] How can I display the definition of a function in Clojure at the REPL?
本文介绍了如何在REPL中显示Clojure中函数的定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找能够让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"))
例如
I'd like to say something like
(print-definition foo)
并获得
(foo [] (if true "true"))
。
推荐答案
源
的替代方法(应通过 clojure.repl / source
1.2.0
时,如果您使用 1.1.0
source
位于 clojure.contrib.repl-utils
。),用于REPL使用, a .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)
code>#'只是一个阅读器宏,从#' foo
到(var foo)
:
#'
is just a reader macro, expanding from #'foo
to (var foo)
:
(macroexpand '#'reduce)
;; => (var reduce)
这篇关于如何在REPL中显示Clojure中函数的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文