How to get function's name as string in Clojure?

后端 未结 3 1523
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 03:50

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 #\         


        
3条回答
  •  自闭症患者
    2021-02-13 04:37

    EDIT: I found a better way Clojure includes a function called demunge. So instead of re-inventing the wheel, just use it ;)

    (clojure.repl/demunge (str map?));; "clojure.core/map?@2b68895c"
    

    Or if you want a prettified version

    (defn- pretty-demunge
      [fn-object]
      (let [dem-fn (demunge (str fn-object))
            pretty (second (re-find #"(.*?\/.*?)[\-\-|@].*" dem-fn))]
        (if pretty pretty dem-fn)))
    
    (pretty-demunge map?);; "clojure.core/map?"
    

    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)

    (clojure.string/replace (second (re-find #"^.+\$(.+)\@.+$" (str string?)))
                            #"\_QMARK\_" "?")
    ; string?
    

    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

    (def foo string?)
    (clojure.string/replace (second (re-find #"^.+\$(.+)\@.+$" (str foo)))
                            #"\_QMARK\_" "?")
    ; string?
    

    Have fun

提交回复
热议问题