(defn sq [x]
(do (println "sq")
(* x x)))
I wanted sq to print it's own name when run; to make it do so I
inserted the name as a string.
Is there some way to dynamically determine the name and so avoid using
the string?
Similarly, is it possible to define a function name-of so that
(name-of sq) returns "sq", etc ?
Thank you,
drc
It is possible to get the name of a the symbol the fn is bound to, but
the fn object itself has no name. Also, fn objects can't take
metadata (but this is supposed to be fixed eventually), so what you
are looking for isn't possible in native Clojure.
Sean
There's this: http://www.mail-archive.com/clo...@googlegroups.com/msg13018.html
Of course some functions don't have a name.
(use 'clojure.contrib.str-utils)
; Stephen C. Gilardi
(defn unmangle
"Given the name of a class that implements a Clojure function,
returns the function's name in Clojure.
Note: If the true Clojure function name contains any underscores
(a rare occurrence), the unmangled name will contain hyphens
at those locations instead."
[class-name]
(.replace
(re-sub #"^(.+)\$(.+)__\d+$" "$1/$2" class-name)
\_ \-))
; Stephen C. Gilardi
(defmacro current-function-name
"Returns a string, the name of the current Clojure function."
[]
`(-> (Throwable.) .getStackTrace first .getClassName unmangle))
I imagine some similar unmangling could be applied to getting the
class-name of an arbitrary function, something like
(unmangle (.toString foo)) ;; but not exactly - this doesn't work
- if you figure that out please post the answer :)
Regards,
Tim.