I'm looking for the ability to have the REPL print the current definition of a function. Is there any way to do this?
For example, given:
(defn foo [] (if true "true"))
I'd like to say something like
(print-definition foo)
and get something along the lines of
(foo [] (if true "true"))
printed.
def is a special form that associates a symbol (x) in the current namespace with a value (7). This linkage is called a var . In most actual Clojure code, vars should refer to either a constant value or a function, but it's common to define and re-define them for convenience when working at the REPL.
So a ClojureScript REPL consists of two parts: the first part is written in Clojure, it handles the REPL UI, and takes care of compiling ClojureScript to JavaScript. This JavaScript code then gets handed over to the second part, the JavaScript environment, which evaluates the code and hands back the result.
A Clojure REPL (standing for Read-Eval-Print Loop) is a programming environment which enables the programmer to interact with a running Clojure program and modify it, by evaluating one code expression at a time.
To start a REPL session in Eclipse, click the Menu option, go to Run As → Clojure Application. This will start a new REPL session in a separate window along with the console output.
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))
A simple print-definition
:
(defn print-definition [v] (:source (meta v))) (print-definition #'foo)
#'
is just a reader macro, expanding from #'foo
to (var foo)
:
(macroexpand '#'reduce) ;; => (var reduce)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With