Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: How to find out the arity of function at runtime?

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

like image 813
GabiMe Avatar asked Nov 08 '09 14:11

GabiMe


People also ask

What is arity 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).

Is Clojure fully functional?

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.

What is arity in programming?

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.

Is Clojure functional programming?

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.


2 Answers

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.

like image 193
Mike Douglas Avatar answered Sep 20 '22 23:09

Mike Douglas


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)) 
like image 21
whocaresanyway Avatar answered Sep 21 '22 23:09

whocaresanyway