読者です 読者をやめる 読者になる 読者になる

Arantium Maestum

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

SICPの勉強 問題1.33

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

filtered-accumulateのiterative process版:

(defn filtered-accumulate [combiner null-value filt f a next b]
  (loop [a a result null-value]
    (cond 
      (> a b)  result
      (filt a) (recur (next a) (combiner (f a) result))
      :else    (recur (next a) result))))

(recursive process版は引数のあまりの多さ・複雑さがおぞましかったので飛ばす)

idiomatic clojure版:

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

sum-of-squares-of-primes:

(defn sosop [n]
  (filtered-accumulate + 0 prime? sq 2 inc n))

product-of-relatively-prime:

(defn porp [n]
  (filtered-accumulate * 1 #(= 1 (gcd n %)) identity 1 inc n))