我正在寻找一个Clojure函数,我们称之为anyargs
,它允许其函数参数忽略多余的参数。例如:
((anyargs cons) :a [:b :c] :d) ; => (:a :b :c)
如果函数参数有多个不同的形式,最好选择最适合的那个。
我正在寻找一个Clojure函数,我们称之为anyargs
,它允许其函数参数忽略多余的参数。例如:
((anyargs cons) :a [:b :c] :d) ; => (:a :b :c)
(defn n-args [f]
(-> f class .getDeclaredMethods last .getParameterTypes alength))
(defn n-args [f]
(apply max
(map #(-> % .getParameterTypes alength)
(-> f class .getDeclaredMethods))))
(defn anyargs [f]
(let [n (n-args f)]
(fn [& args] (apply f (take n args)))))
#(apply f (take n %&))
我认为你需要黑客攻击它。
(defn max-arities [f]
(reduce
#(merge-with max % {(.getName %2) (alength (.getParameterTypes %2))})
{}
(seq (.getDeclaredMethods (class +)))))
(defn anyargs [f]
(let [accept (if (instance? clojure.lang.RestFn f)
identity
(partial take ((max-arities f) "invoke")))]
(fn [& args] (apply f (accept args)))))
((anyargs cons) :a [:b :c] :d) ;=> (:a :b :c)
((anyargs +) 1 2 3 4 5 6 7 8 9 10) ;=> 55