Can a function determine it's own name at runtime?

1,947 views
Skip to first unread message

David Cabana

unread,
Dec 20, 2009, 4:55:37 PM12/20/09
to clo...@googlegroups.com
Suppose we define a function called sq:

(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

Sean Devlin

unread,
Dec 20, 2009, 5:34:58 PM12/20/09
to Clojure
This question is tricky to answer, do to the way things are bound in
Clojure.

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

.Bill Smith

unread,
Dec 20, 2009, 5:45:28 PM12/20/09
to Clojure
On Dec 20, 3:55 pm, David Cabana <drcab...@gmail.com> wrote:
> Suppose we define a function called sq:
>
> (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?

There's this: http://www.mail-archive.com/clo...@googlegroups.com/msg13018.html

Of course some functions don't have a name.

Timothy Pratley

unread,
Dec 20, 2009, 5:50:05 PM12/20/09
to Clojure
Regarding current function, Stephen posted this code a whie ago so I
don't think he'll mind me regurgitating it for you:

(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.

Rob Jens

unread,
Aug 1, 2013, 4:15:00 PM8/1/13
to clo...@googlegroups.com, timothy...@gmail.com
Thanks Timothy/Stephen, that was very useful to me :)

Op zondag 20 december 2009 23:50:05 UTC+1 schreef Timothy Pratley:
Reply all
Reply to author
Forward
0 new messages