Variable capture.

100 views
Skip to first unread message

Asbjørn Bjørnstad

unread,
May 10, 2008, 1:12:44 PM5/10/08
to Clojure
Hi,
I'd like to write a macro that uses variable capture to present an
environment to a function.

Something like:

(defn foo [z]
(with-env
(+ x z)))

to expand to :

(defn foo [z]
(fn [env]
(let [x (env :x)]
(+ x z))))

I've tried simply

(defmacro my-env [& body]
`(fn [env]
(let [x (env :x)
y (env :y)]
~@body)))

but get a "Can't use qualified name as parameter" error which from
earlier postings have to do with... variable capture.

Any tips?
--
-asbjxrn

Asbjørn Bjørnstad

unread,
May 11, 2008, 12:31:24 AM5/11/08
to Clojure
The solution is to use ~'x and ~'y, but also to use gensyms for env (I
had tried ~'x, but still got the error from env which fooled me into
thinking ~'x did not work):

(defmacro my-env [& body]
`(fn [env#]
(let [~'x (env# :x)
~'y (env# :y)]
~@body)))
--
-asbjxrn

Reply all
Reply to author
Forward
0 new messages