開発環境
計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原著: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の第1章(手続きによる抽象の構築)、1.3(高階手続きによる抽象)、1.3.1(引数としての手続き)、問題1.33-a、b.を取り組んでみる。
その他参考書籍
問題1.33-a、b.
コード(Emacs)
(begin
(load "procedures.scm")
(newline)
(define (p x) (display x) (newline))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(if (> (square test-divisor) n)
n
(if (divides? test-divisor n)
test-divisor
(find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
;; 反復的プロセス
(define (filtered-accumulate pred combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(if (pred a)
(iter (next a) (combiner (term a) result))
(iter (next a) result))))
(iter a null-value))
(define (id x) x)
(define (inc x) (+ x 1))
;; a.
(define (sum-of-prime-squares a b)
(filtered-accumulate prime? + 0 id a inc b))
;; b.
(define (b n) (filtered-accumulate (lambda (m)
(= (gcd n m) 1))
* 1 id 1 inc (- n 1)))
(p (sum-of-prime-squares 2 100))
(p (b 100))
'done)
入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))
$ ksi < sample33.scm ksi> 1060 426252881942771063138176712755660145456313428952105524817872601 => done ksi> $
0 コメント:
コメントを投稿