Arantium Maestum

プログラミング、囲碁、読書の話題

SICPの勉強 問題1.32

SICP1.3.1の問題1.32を解いてみる。

accumulateのrecursive process版:

(defn accumulate [combiner null-value f a next b]
  (if (> a b)
    null-value
    (combiner (f a)
       (accumulate combiner null-value f (next a) next b))))

iterative process版:

(defn accumulate [combiner null-value f a next b]
  (loop [a a result null-value]
    (if (> a b)
      result
      (recur (next a) (combiner (f a) result)))))

idiomatic clojure版:

(defn accumulate [combiner null-value f a next b]
  (->> (iterate next a)
       (take-while #(<= % b))
       (map f)
       (reduce combiner null-value)))

sumの定義:

(defn sum [f a next b]
  (accumulate + 0 f a next b))

productの定義:

(defn product [f a next b]
  (accumulate * 1 f a next b))