2015年3月24日火曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.1(データ抽象入門)、2.1.4(拡張問題: 区間算術演算)、問題 2.10.を解いてみる。

その他参考書籍

問題 2.10.

コード(BBEdit, Emacs)

(define make-interval
  (lambda (a b) (cons a b)))

(define lower-bound
  (lambda (interval) (car interval)))

(define upper-bound
  (lambda (interval) (cdr interval)))

(define print-interval
  (lambda (interval)
    (display "(")
    (display (lower-bound interval))
    (display ", ")
    (display (upper-bound interval))
    (display ")")
    (newline)))

(define interval (make-interval 1 2))

(define sub-interval
  (lambda (x y)
    (make-interval (- (lower-bound x) (upper-bound y))
                   (- (upper-bound x) (lower-bound y)))))
                      
(define add-interval
  (lambda (x y)
    (make-interval (+ (lower-bound x) (lower-bound y))
                   (+ (upper-bound x) (upper-bound y)))))

(define mul-interval
  (lambda (x y)
    ((lambda (p1 p2 p3 p4)
       (make-interval (min p1 p2 p3 p4)
                      (max p1 p2 p3 p4)))
     (* (lower-bound x) (lower-bound y))
     (* (lower-bound x) (upper-bound y))
     (* (upper-bound x) (lower-bound y))
     (* (upper-bound x) (upper-bound y)))))

(define div-interval
  (lambda (x y)
    (if (<= (* (lower-bound y) (upper-bound y)) 0)
        (error "zero division")
        (mul-interval x
                      (make-interval (/ 1.0 (upper-bound y))
                                     (/ 1.0 (lower-bound y)))))))

(define width
  (lambda (interval)
    (/ (- (upper-bound interval)
          (lower-bound interval))
       2)))

(define add-interval-width
  (lambda (x-width y-width) (+ x-width y-width)))

(define i0 (make-interval 1 1))
(define i1 (make-interval 0 1))
(define i2 (make-interval 1 2))

(print-interval (div-interval i1 i0))
(print-interval (div-interval i0 i1))

入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))

$ gosh sample10.scm
(0.0, 1.0)
gosh: "error": zero division
$

0 コメント:

コメントを投稿