How can you get function's name as string in Clojure?
What I have so far doesn't look anywhere near idiomatic:
(defn fn-name
[f]
(first (re-find #"(?<=\$)([^@]+)(?=@)" (str f))))
(defn foo [])
(fn-name foo) ;; returns "foo"
EDIT: With the provided hints I put together a basic macro that does what I want. Does it look better?
(defmacro fn-name
[f]
`(-> ~f var meta :name str))
I suggested an improvement to @carocad's answer in a comment. Since I also needed to do this, and I needed to do it in both
clj
andcljs
, here is what I came up with:Note that
cljs.core
has its owndemunge
built in and can't accessclojure.main
.Edit
Note that when you do
(with-meta a-fn {...})
, it returns aclojure.lang.AFunction
in clojure, which hides the underlying name and namespace information. There may be other situations like that, I'm not sure. Withfn
literal forms, you can do^{...} (fn ...)
instead of(with-meta (fn ...) {...})
and it won't return aclojure.lang.AFunction
, but that workaround won't work with predefined functions. I haven't tested any of this in clojurescript to see if it works the same way.Note also that anonymous functions in clojure will always end in
fn
, as in"my-ns.core/fn"
. Normally these functions would have a"--[0-9]+"
at the end, but the regex above removes that. You could modify the function above and make an exception for anonymous functions. As long as the lambda has an internal name, that will be used, e.g.:Again, I haven't tested any of these notes in clojurescript yet.
For functions defined with the
defn
form:This requires access to the var, rather than just the function value the var holds.
EDIT: I found a better way Clojure includes a function called demunge. So instead of re-inventing the wheel, just use it ;)
Or if you want a prettified version
I think there is a more clean way to do this. I ran into the same problem of wanting to know the name of function gotten as an argument in a function. I couldn't use the macro because I needed to map it so here is what I've got: (assume string? is the function passed as argument)
Of course this is not a complete solution but I'm sure you can work your way through from here. Basically Clojure mangles the function name into something it can use. So the basic though is obviously: you need to unmangle that ! Which is pretty easy since str works on any function :D, returning the mangled name of the function.
By the way, this also works
Have fun