how can i know if a function name provided as string is callable or not in the current context? something like:
开发者_如何学C(callable? "asdasd") ;; false
(callable? "filter") ;; true
thanks
You are looking for resolve,
(resolve (symbol "asd"))
returns nil
(resolve (symbol "filter"))
return #'clojure.core/filter
To check if a var is a function (credit goes to @amalloy):
(-> s symbol resolve deref ifn?)
Chances are if you need this, you're doing something wrong, but...
(defn callable?
[s]
(let [obj (try (eval (symbol s)) (catch Exception e))]
(and obj (fn? obj))))
(defn callable? [name]
(clojure.test/function? (symbol name)))
UPD. I found out that fn?
checks only for interface Fn
and doesn't work for resolved symbol. Though, clojure.test/function?
does what is needed, so I updated an example.
精彩评论