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

前端 未结 7 1589
野趣味
野趣味 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条回答
  •  忘掉有多难
    2021-01-31 02:46

    Building on @whocaresanyway's solution:

    (defn provided
      [cond fun x]
      (if cond
        (fun x)
        x))
    
    (defn append
      [xs x]
      (conj (vec xs) x))
    
    (defn arity-of-method
      [method]
      (->> method .getParameterTypes alength))
    
    (defn arities
      [fun]
      (let [all-declared-methods (.getDeclaredMethods (class fun))
            methods-named (fn [name]
                            (filter #(= (.getName %) name) all-declared-methods))
            methods-named-invoke (methods-named "invoke")
            methods-named-do-invoke (methods-named "doInvoke")
            is-rest-fn (seq methods-named-do-invoke)]
        (->> methods-named-invoke
             (map arity-of-method)
             sort
             (provided is-rest-fn
                       (fn [v] (append v :rest))))))
    

提交回复
热议问题