On 28/03/2012 18:15, Shantanu Kumar wrote:
On Mar 28, 8:57 pm, Ram Krishnan <kriyat...@gmail.com> wrote:
> Did you just need the name of the function? something like this?
Sorry, I should explained using code what I am looking for:
(defmacro find-name []
;; some magic here
..)
(defn foo []
..
(println (find-name)) ; should print "foo"
..)
I am looking for a way to write the `find-name` macro. So, you can see
I want to use it with regular functions defined using `defn`.
Shantanu
My solution:
(defmacro find-name []
(let [[[sym _]] (filter (fn [[_ binding]]
(zero? (.idx binding)))
&env)]
`'~sym))
(defn foo []
(println (find-name)))
(foo)
=> foo
nil
One has access to the environment in which the macro was expanded
through the relatively unknown `&env`. The value of `&env` is a map of
symbols to bindings. The bindings are numbered, so the binding with 0
as index (`.idx`) is the function that is being defined. Remember that
(defn x [] ..) roughly (ignoring metadata) expands to:
(def x (fn x [] ..))
Even in the following case (to my surprise), the `foo`-binding still
has index 0:
(let [x 1]
(defn foo []
(let [y 2]
(println (find-name)))))
This is quite 'hackish' and should not be relied upon.
dewinant
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en