我應該使用哪個更好?:(減少+ ...)或(應用+ ...)?
(apply + (filter prime? (range 1 20)))
或
(reduce + (filter prime? (range 1 20)))
編輯:這是首要Clojure中從優化工具包中的源。
(defn prime? [n]
(cond
(or (= n 2) (= n 3)) true
(or (divisible? n 2) (< n 2)) false
:else
(let [sqrt-n (Math/sqrt n)]
(loop [i 3]
(cond
(divisible? n i) false
(< sqrt-n i) true
:else (recur (+ i 2)))))))
[Clojure:reduce vs. apply]的可能重複(http://stackoverflow.com/questions/3153396/clojure-reduce-vs-apply)。鏈接的問題比這個更新,但它有IMO更好的答案,所以我提名它爲倖存者。 – amalloy 2012-05-29 19:14:56