Clojure: determine if a function exists

南笙酒味 提交于 2019-12-05 20:22:42

问题


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


回答1:


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?)



回答2:


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:


(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.



来源:https://stackoverflow.com/questions/7715800/clojure-determine-if-a-function-exists

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