Clojure: determine if a function exists

天涯浪子 提交于 2019-12-04 03:03:06
Hamza Yerlikaya

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!