4Clojure 58题 的问题陈述如下:
编写一个函数,允许您创建函数组合。参数列表应该接受可变数量的函数,并创建一个从右到左应用它们的函数。
(= [3 2 1] ((__ rest reverse) [1 2 3 4]))
(= 5 ((__ (partial + 3) second) [1 2 3 4]))
(= true ((__ zero? #(mod % 8) +) 3 5 7 9))
(= "HELLO" ((__ #(.toUpperCase %) #(apply str %) take) 5 "hello world"))
这里__
应该被解决方案替换。
在这个问题中,不应使用函数comp
。
我找到的解决方案是:
(fn [& xs]
(fn [& ys]
(reduce #(%2 %1)
(apply (last xs) ys) (rest (reverse xs)))))
它起作用了。但我真的不太明白这里的reduce是如何工作的。它如何代表(apply f_1 (apply f_2 ...(apply f_n-1 (apply f_n args))...))?