Search code examples
clojureread-eval-print-loop

A Clojure function that prints the “fully expanded form before evaluation”?


Is there a Clojure function that does for any function what macroexpand-all does for a macro?

In SICP, Abelson & Sussman give a demonstration of this that they call the “linear recursive process”.

In other words, if we give:

(factorial 6)

the function would print (and not evaluate):

(* 6 (* 5 (* 4 (* 3 (* 2 (1))))))

Essentially, I am trying to “see” the data structure any function “builds up” prior to evaluation.


I think this would be an interesting way for beginners (myself) to see what the Reader* is building up just before it passes things on to the Evaluator*.

*Not sure I’m using the right terms here.


Solution

  • Function tracing can be done without programming. It is, for example, available in the Cider extension to Emacs. https://docs.cider.mx/cider/debugging/tracing.html

    I have loaded my factorial program into Emacs, and placed my cursor on the factorial function.

     (ns factorial.core
        (:gen-class))
    
     (defn factorial [n]
        (if (zero? n)
         1
         (* n (factorial (dec n)))))
    
     (defn -main
        "A factorial program."
        [& args]
    
        (let [n 6] 
           (println "The factorial of " n "is" (factorial n))))
    
                 M-x cider-jack-in
    
     REPL:  (in-ns 'factorial.core)
    
                 C-c M-t v, select factorial when prompted
    
            (factorial 3)
    

    enter image description here