Hi!
Am 19.08.2009 um 10:24 schrieb lancecarlson:
> Is there a way to introspect a function to get its arity? I know some
> functions have an arbitrary amount of arguments, but knowing the count
> on finite argument lists and whether or not a function accepts an
> infinite list would be very useful. Also, hints on what types a
> functions arguments accept would be nice to parse through. I don't
> need the docs for particular functions, but to be able to use this
> information in my code. Ideas?
Inspecting the var's metadata is probably the best way to do this.
If you're not dealing with vars, but anonymous functions, here's a
hackish piece of code that gathers arity information via reflection:
(defn arities [f]
(let [methods (.getDeclaredMethods (class f))
count-params (fn [m] (map #(count (.getParameterTypes %))
(filter #(= m (.getName %))
methods)))
invokes (count-params "invoke")
do-invokes (map dec (count-params "doInvoke"))
arities (sort (distinct (concat invokes do-invokes)))]
(if (seq do-invokes)
(concat arities [:more])
arities)))
user> (arities map)
(2 3 4 :more)
user> (arities (fn ([a b]) ([a b c d]) ([a b c d e f & more])))
(2 4 6 :more)
Beware! This snippet relies on unexposed details of clojure's current
implementation. It might stop working tomorrow, so it's definitely not
intended for production use, but it might help with debbuging/exploring.
Kind Regards,
achim
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---