On Tue, Jan 03, 2012 at 07:22:22PM -0800, Trevor wrote:
> hmmm.... macro question:
>
> ; here's a macro that assembles many puts. It serves no purpose to me
> (and doesn't even make sense in its current form). It's just something
> I hit playing around and learning macros.
>
> (defmacro doto-putter [x y xs]
> `(doto (java.util.HashMap.)
> (.put ~x ~y)
> ~@(for [[k v] xs]`(.put ~k ~v))))
>
> user=> (doto-putter "c" 3 {"a" 1 "b" 2})
> #<HashMap {b=2, c=3, a=1}>
>
> however:
>
> =>(defn omg [x y xs](doto-putter x y xs))
> CompilerException java.lang.IllegalArgumentException: Don't know how
> to create ISeq from: clojure.lang.Symbol, compiling:(NO_SOURCE_PATH:2)
>
> I'm thinking the issue seems to be that it's not resolving xs because
> this works:
>
> (defmacro doto-putter [x y]
> `(doto (java.util.HashMap.)
> (.put ~x ~y)
> ~@(for [[k v]{"a" 1 "b" 2}]`(.put ~k ~v))))
>
> user=> (defn omg [x y](doto-putter x y))
> #'user/omg
>
> user=>(omg "c" 3)
> #<HashMap {b=2, c=3, a=1}>
>
> what am I missing? None of my other macros have this problem.
Keep in mind that you are trying to iterate through xs at compile time.
All you have at that point is a symbol, so effectively you are trying
this:
(for [[k v] 'xs] ...)
That's why you are getting the error above; you are trying to iterate
through a symbol. There isn't a way around this, because it's impossible
to know the keys/values at compile time.
What you need to do instead is generate the code to iterate through the
map instead of actually iterating through at compile time. Something
like this:
(defmacro doto-putter [x y xs]
`(let [h# (java.util.HashMap.)]
(.put h# ~x ~y)
(dorun (for [[k# v#] ~xs]
(.put h# k# v#)))
h#))
Hope that helps,
Robert
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en