2014年6月5日木曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.5(汎用演算のシステム)、2.5.3(例: 記号代数)、多項式の算術演算、項リストの表現、記号代数における型の階層構造、拡張問題: 有理関数、問題 2.94.を解いてみる。

その他参考書籍

問題 2.94.

コード(BBEdit, Emacs)

sample.scm

#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-

(define (install-polynomial-package)
  (define (remainder-terms a b)
    (cadr (div-terms a b)))
  (define (gcd-terms a b)
    (if (empty-termlist? b)
        a
        (gcd-terms b (remainder-terms a b))))

  (define (gcd-poly p1 p2)
    (if (same-variable? (variable p1)
                        (variable p2))
        (make-poly (variable p1)
                   (gcd-terms (term-list p1)
                              (term-list p2)))
        (error "Polys not in same var -- GCD-POLY"
               (list p1 p2))))

  (put 'gcd '(polynomial polynomial)
       (lambda (p1 p2)
         (tag (gcd-poly p1 p2))))
  'done)

(define (install-scheme-number-package)
  (put 'gcd '(scheme-number scheme-number)
     (lambda (a b)
       (tag (gcd a b))))
  'done)

(define (greatest-common-divisor a b)
  (apply-generic 'gcd a b))

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

$ ./sample.scm
$

手計算でテスト。

(greatest-common-divisor p1 p2)

(x (gcd-terms ((4 1) (3 -1) (2 -2) (1 2))
              ((3 1) (1 -1))))

(x (gcd-terms ((3 1) (1 -1))
              (remainder-terms ((4 1) (3 -1) (2 -2) (1 2))
                               ((3 1) (1 -1)))))

(x (gcd-terms ((3 1) (1 -1))
              ((3 -1) (2 -1) (1 2))))

(x (gcd-terms ((3 -1) (2 -1) (1 2))
              (remainder-terms ((3 1) (1 -1))
                               ((3 -1) (2 -1) (1 2)))))

(x (gcd-terms ((3 -1) (2 -1) (1 2))
              ((2 -1) (1 1))))

(x (gcd-terms ((2 -1) (1 1))
              (remainder-terms ((3 -1) (2 -1) (1 2))
                               ((2 -1) (1 1)))))

(x (gcd-terms ((2 -1) (1 1))
              ((2 -2) (1 2))))

(x (gcd-terms ((2 -2) (1 2))
              (remainder-terms ((2 -1) (1 1))
                               ((2 -2) (1 2)))))

(x (gcd-terms ((2 -2) (1 2))
              ()))

(x ((2 -2) (1 2)))

0 コメント:

コメントを投稿