開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Scheme (プログラミング言語)
- Gauche (処理系)
計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の1(手続きによる抽象の構築)、1.3(高階手続きによる抽象)、1.3.1(引数としての手続き)、問題 1.32-b.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
問題 1.32-b.
a.は反復的プロセスで手続きを書いたので、今回は再帰的プロセスで。
コード(BBEdit, Emacs)
sample.scm
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner
null-value
term
(next a)
next
b))))
(define (sum term a next b)
(accumulate + 0 term a next b))
(define (product term a next b)
(accumulate * 1 term a next b))
;; 合成手続き
(define (square x) (* x x))
(define (inc n) (+ n 1))
(define (identity x) x)
(define (sum-integers a b)
(sum identity a inc b))
(define (pi-sum a b)
(define (pi-term x)
(/ 1.0 (* x (+ x 2))))
(define (pi-next x)
(+ x 4))
(sum pi-term a pi-next b))
(define (factorial n)
(product identity 1 inc n))
(define (pi-product a b)
(define (pi-term x)
(/ (* (- x 1.0)
(+ x 1.0))
(square x)))
(define (pi-next x) (+ x 2))
(product pi-term a pi-next b))
;; テスト
(print "sum手続き")
(print "1 + 2 + … + 10 = " (sum-integers 1 10))
(print "πの近似値")
(for-each (lambda (x)
(print (* 8 (pi-sum 1 x))))
'(100 1000 10000 100000 1000000))
(print "product手続き")
(print "10! = " (factorial 10))
(print "πの近似値")
(for-each (lambda (x)
(print (* 4 (pi-product 3 x))))
'(100 1000 10000 100000 1000000))
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ ./sample.scm sum手続き 1 + 2 + … + 10 = 55 πの近似値 3.1215946525910105 3.139592655589783 3.141392653591793 3.141572653589795 3.141590653589793 product手続き 10! = 3628800 πの近似値 3.1573396892175642 3.143163842419204 3.1417497371492957 3.141608361592229 3.141594224381283 $
0 コメント:
コメントを投稿