(def a 10)
(def b 20)
(println "answer:" (* a b))
These tend to look like:
(println "the current value of a is" a)
or equivalently:
(println "the current value of" (quote a) "is" a)
This rapidly gets old, particularly if what we want is to look at the values of complex expressions:
(println "the current value of" (quote (* a b)) "is" (* a b))
We can make the repeated text go away with a function:
(defn debug-fn [exp val]
(println "the current value of" exp "is" val))
(debug-fn '(* a a) (* a a))
Even if we're prepared to use run-time evaluation, we have to jump through hoops to make sure that the expression gets evaluated in the correct environment. Which is worse.
Analogues of this exact problem drive me up the wall in every language which doesn't have macros. It's such a useful construct that I'm surprised that there isn't a special way to do it.
In the absence of such a special feature, what would be nice, is if we could say to the compiler:
" every time you see something like
imagine I'd written(debug (* a a))
instead. "(println "the current value of" (quote (* a a)) "is" (* a a))
And in a lisp, we can:
(defmacro debug [var]
`(println "the current value of " (quote ~var) "is" ~var))
(debug a) (debug b)
(debug *)
(debug (* a b)) (debug (* 1 2 3 4))
(println (macroexpand '(debug a)))
or we could be smug:
(debug (macroexpand '(debug a)))
No comments:
Post a Comment