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

前端 未结 7 1414
野趣味
野趣味 2021-01-31 02:08

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 C

7条回答
  •  梦毁少年i
    2021-01-31 02:30

    Actually it also works on macros:

    (defn arg-count [f]
      (let [m (first (.getDeclaredMethods (class f)))
            p (.getParameterTypes m)]
        (alength p)))
    
    (defmacro my-macro [])
    
    (arg-count @#'my-macro)
    ; 2
    

    Why 2? Because every macro has two implicit arguments &form and &env respectively.

提交回复
热议问题