This works.
(defn dump1 [string]
(println string "=" (load-string string)))
(dump1 "(+ 1 2)")
Note how I had to put the expression passed to dump1 in quotes to make a string.
I'm wondering if there is a way to avoid that using a macro. The hard
part is printing the expression. The following doesn't work. It
outputs "3 = 3".
(defmacro dump2 [expr]
`(let [value# ~expr]
(pr ~expr)
(println " =" value#)))
(dump2 (+ 1 2))
--
R. Mark Volkmann
Object Computing, Inc.
> I'm wondering if there is a way to avoid that using a macro. The hard
> part is printing the expression. The following doesn't work. It
> outputs "3 = 3".
>
> (defmacro dump2 [expr]
> `(let [value# ~expr]
> (pr ~expr)
> (println " =" value#)))
> (dump2 (+ 1 2))
All it takes to make it work is a slight modification:
(defmacro dump [expr]
`(let [value# ~expr]
(pr (quote ~expr))
(println " =" value#)))
(dump (+ 1 2))
prints:
(+ 1 2) = 3
Konrad.
Thanks! It looks like I don't need the let now. Does a macro have to
evaluate to one form? For example, this works, but it seems I can't
drop the do.
(defmacro dump [expr]
`(do
(print (quote ~expr))
(println " =" ~expr)))
How about:
(defmacro dump [expr]
`(println '~expr "=" ~expr))
> R. Mark Volkmann
--
! Lauri
> Thanks! It looks like I don't need the let now.
Indeed.
> Does a macro have to evaluate to one form? For example, this works,
> but it seems I can't
> drop the do.
Yes, a macro has to evaluate to one form. This is actually not so
much a condition on macros as a consequence of the fact that a macro,
like any function, has a single return value. What else could that
reasonably be but a form?
Konrad.
Am 24.03.2009 um 16:00 schrieb Mark Volkmann:
> Thanks! It looks like I don't need the let now.
But there are reasons to keep it! Eg. returning the expression
result!
(defmacro dump
[expr]
`(let [value# ~expr]
(println (pr-str (quote ~expr)) "=" (pr-str value#))
value#))
Then you can mix in your dump macro where you want.
Your version always returns nil.
Or you can have a look at clojure.contrib.trace.
Sincerely
Meikel