2015年5月30日土曜日

開発環境

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

その他参考書籍

問題2.66.

コード(Emacs)

(define equal?
  (lambda (a b)
    (if (and (pair? a) (pair? b))
        (and (eq? (car a) (car b))
             (equal? (cdr a) (cdr b)))
        (eq? a b))))
(define entry (lambda (tree) (car tree)))
(define left-branch (lambda (tree) (cadr tree)))
(define right-branch (lambda (tree) (caddr tree)))
(define make-tree
  (lambda (entry left right)
    (list entry left right)))

(define list->tree
  (lambda (elements)
    (car (partial-tree elements (length elements)))))

(define partial-tree
  (lambda (elts n)
    (if (= n 0)
        (cons (quote ()) elts)
        (let ((left-size (quotient (- n 1) 2)))
          (let ((left-result (partial-tree elts left-size)))
            (let ((left-tree (car left-result))
                  (non-left-elts (cdr left-result))
                  (right-size (- n (+ left-size 1))))
              (let ((this-entry (car non-left-elts))
                    (right-result (partial-tree (cdr non-left-elts)
                                                right-size)))
                (let ((right-tree (car right-result))
                      (remaining-elts (cdr right-result)))
                  (cons (make-tree this-entry left-tree right-tree)
                        remaining-elts)))))))))

(define key (lambda (record) (car record)))
(define value (lambda (record) (cdr record)))
(define make-record (lambda (key value) (cons key value)))

(define lookup
  (lambda (given-key set-of-records)
    (cond ((null? set-of-records) #f)
          ((= given-key (key (entry set-of-records)))
           (value (entry set-of-records)))
          ((< given-key (key (entry set-of-records)))
           (lookup given-key (left-branch set-of-records)))
          ((> given-key (key (entry set-of-records)))
           (lookup given-key (right-branch set-of-records))))))

(define r1 (make-record 1 (quote scheme)))
(define r2 (make-record 2 (quote c)))
(define r3 (make-record 3 (quote python)))
(define r4 (make-record 4 (quote javascript)))
(define r5 (make-record 5 (quote scala)))
(define records (list->tree (list r1 r2 r3 r4 r5)))

(lookup 0 records)
(lookup 1 records)
(lookup 2 records)
(lookup 3 records)
(lookup 4 records)
(lookup 5 records)
(lookup 10 records)
(lookup 1 (list->tree (quote ())))

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

$ kscheme < sample66.scm
kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> #f
kscm> scheme
kscm> c
kscm> python
kscm> javascript
kscm> scala
kscm> #f
kscm> #f
kscm> $

0 コメント:

コメントを投稿