yayitswei
yayitswei

Reputation: 4687

Recommended ways to debug Clojure functions?

My current method: if there's a function that I know has an bug, I copy bits and pieces of it into the REPL and evaluate to see if the output is what I expect. To set it up, I have to def the arguments to the function as dummy input. Not terribly time-consuming, but I know there's a more efficient way.

Any suggestions?

Upvotes: 7

Views: 928

Answers (5)

Kevin Zhu
Kevin Zhu

Reputation: 2836

Function version of def-let, some credit goes to here.

(defn def-let [aVec]
  (if-not (even? (count aVec))
    aVec
    (let [aKey (atom "")       
          counter (atom 0)]
      (doseq [item aVec]
        (if (even? @counter) 
          (reset! aKey  item)           
          (intern *ns*  (symbol @aKey)  (eval item)))
        ;   (prn  item)       
    (swap! counter inc)))))

Usage: Needs to quote the content with a quotation, e.g.

(def-let '[a 1 b 2 c (atom 0)])

Upvotes: 1

Takahiro Hozumi
Takahiro Hozumi

Reputation: 711

I wrote an tracing library which can show you what value every element returned.
http://github.com/hozumi/eyewrap

Upvotes: 1

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

for bugs spanning several functions I like the Trace macro for reporting the calls and returns of each function.

Upvotes: 1

John Lawrence Aspden
John Lawrence Aspden

Reputation: 17470

Does this macro help? It turns a let into a series of defs, so that you can evaluate the subexpressions:

(defmacro def-let
  "like let, but binds the expressions globally."
  [bindings & more]
  (let [let-expr (macroexpand `(let ~bindings))
        names-values (partition 2 (second let-expr))
        defs   (map #(cons 'def %) names-values)]
    (concat (list 'do) defs more)))

I wrote an explanation here: http://www.learningclojure.com/2010/09/astonishing-macro-of-narayan-singhal.html

Upvotes: 4

yayitswei
yayitswei

Reputation: 4687

After reading up on this, my new favorite method is to add

(swank.core/break)

inside the function and inspect values by pressing 't'. (I'm using swank-clojure)

Source: http://hugoduncan.org/post/2010/swank_clojure_gets_a_break_with_the_local_environment.xhtml

Upvotes: 2

Related Questions