Given a function object or name, how can I determine its arity? Something like (arity func-name)
.
I hope there is a way, since arity is pretty central in Clojure
This is where multi-arity functions come in in Clojure (an arity is simply the number of arguments that a function can take).
Clojure is a functional programming language. It provides the tools to avoid mutable state, provides functions as first-class objects, and emphasizes recursive iteration instead of side-effect based looping.
Arity (/ˈærɪti/ ( listen)) is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science. In mathematics, arity may also be named rank, but this word can have many other meanings in mathematics.
Clojure is a dialect of Lisp, and shares with Lisp the code-as-data philosophy and a powerful macro system. Clojure is predominantly a functional programming language, and features a rich set of immutable, persistent data structures.
The arity of a function is stored in the metadata of the var.
(:arglists (meta #'str)) ;([] [x] [x & ys])
This requires that the function was either defined using defn
, or the :arglists
metadata supplied explicitly.
Sneaky reflection:
(defn arg-count [f] (let [m (first (.getDeclaredMethods (class f))) p (.getParameterTypes m)] (alength p)))
Or :
(defn arg-count [f] {:pre [(instance? clojure.lang.AFunction f)]} (-> f class .getDeclaredMethods first .getParameterTypes alength))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With