Clojure: determine if a function exists

2019-04-06 06:46发布

how can i know if a function name provided as string is callable or not in the current context? something like:

(callable? "asdasd") ;; false
(callable? "filter") ;; true

thanks

标签: clojure lisp
3条回答
Deceive 欺骗
2楼-- · 2019-04-06 07:20

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))))
查看更多
唯我独甜
3楼-- · 2019-04-06 07:22

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?)
查看更多
孤傲高冷的网名
4楼-- · 2019-04-06 07:26
(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.

查看更多
登录 后发表回答