Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display the definition of a function in Clojure at the REPL?

Tags:

clojure

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.

like image 391
Tim Visher Avatar asked Sep 23 '10 22:09

Tim Visher


People also ask

What is def Clojure?

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.

How does Clojure REPL work?

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.

What is Clojure REPL?

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.

How do I launch REPL in Clojure?

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.


1 Answers

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) 
like image 132
15 revs Avatar answered Oct 02 '22 03:10

15 revs