Hi!
A while back, I was implementing some datastructures using functions and
macros.
While implementing hashmaps, I stumbled upon a problem:
(ns hmap)
(defmacro hmap [& kvs]
"Returns an immutable hashmap.
Keys must be compile-time constants."
(if (even? (count kvs))
(let [tups (partition 2 kvs)
keys (mapv first tups)
kvs+ (concat kvs [::keys keys])]
`(fn [k#]
(case k# ~@kvs+)))
(throw (Exception. "hmap takes an EVEN number of args"))))
(comment ;; USAGE
(def m (hmap :a 1 :b 2))
;; => #'hmap/m
(m ::keys)
;; => [:a :b]
(m :a)
;; => 1
(m :c)
;; => IllegalArgumentException No matching clause: :c
)
*(m ::keys)* returns *nil* if *(mapv first tups)* is changed to *(map first
tups)*.
I had originally used *map*, but seeing that it was not behaving as
expected,
my friend Divyanshu suggested converting the *keys* binding into a vector,
which made it work.
Some questions -
* Is this because of the lazy seq not being realized in the context of the
macro?
* Is this correct/expected behavior?
Thanks!
--
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
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.