Last Updated: February 25, 2016
·
392
· arichiardi

Method arity in Clojure

Given a function, named or anonymous, using some clojure.reflect hocus-pocus we can obtain its arity or, even better, all of its arities with:

(defn arities
  "Returns the parameter count of each invoke method of the input f. This function does NOT detect variadic functions and does NOT work with macros."
  [f]
  {:pre [f]}
  (let [invokes (filter
                #(re-find (re-pattern "invoke") (.getName %1))
                (-> f class .getDeclaredMethods))]
    (map #(alength (.getParameterTypes %1)) invokes)))

1 Response
Add your response

Same same but different :)

(defn  arg-count [f]
  {:pre [(instance? clojure.lang.AFunction f)]}
  (-> f class .getDeclaredMethods first .getParameterTypes alength))
over 1 year ago ·