This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2018-01-26
Channels
- # arachne (80)
- # beginners (76)
- # boot (16)
- # cider (66)
- # cljs-dev (62)
- # cljsjs (1)
- # clojure (106)
- # clojure-dev (5)
- # clojure-greece (2)
- # clojure-italy (9)
- # clojure-russia (1)
- # clojure-spec (61)
- # clojure-uk (130)
- # clojurescript (21)
- # core-async (9)
- # cursive (3)
- # datomic (37)
- # events (41)
- # figwheel (31)
- # fulcro (27)
- # hoplon (1)
- # jobs (2)
- # lumo (11)
- # off-topic (155)
- # re-frame (71)
- # reagent (27)
- # ring-swagger (3)
- # shadow-cljs (132)
- # spacemacs (5)
- # specter (1)
- # sql (37)
- # test-check (10)
- # uncomplicate (5)
- # unrepl (2)
- # yada (3)
Would it be possible to have a function in the core to resolve function arities at runtime? Or is there such method already? It seems that can be done via reflection, but it’s really hacky.
For example in Ring, there are handler/middleware with 1, 2 or 1 & 2 arities. Would be nice to be able to inspect ’em and fail fast instead of first invocation (to some particular path).
With some googling, this seems to be the way to do it today:
(import '(java.lang.reflect Method))
(defn arities [f]
(let [methods (-> f class .getDeclaredMethods)
var-arg? (some #(-> ^Method % .getName (= "getRequiredArity")) methods)
counts (->> methods
(filter #(= (.getName ^Method %) "invoke"))
(map #(.getParameterCount ^Method %))
(set))]
(cond-> counts var-arg? (conj :*))))
(defn kikka ([_]) ([_ _]))
(doseq [f [kikka
(fn kukka ([_ _]) ([_ _ _ _ _]) ([_ _ _ _ _ _ _ & _]))
#()
#(%5 %7)
#(%)
#(%&)]]
(println (arities f)))
; #{1 2}
; #{:* 2 5}
; #{0}
; #{7}
; #{1}
; #{:*}
No plans to do that
Generally I find that when you get to the point where you are asking that question, probably you’re doing things you shouldn’t