2015年4月16日木曜日

開発環境

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

その他参考書籍

問題2.29-b.

コード(BBEdit, Emacs)

(define (make-mobile left right)
  (list left right))

(define (make-branch length structure)
  (list length structure))

(define left-branch
  (lambda (mobile)
    (car mobile)))

(define right-branch
  (lambda (mobile)
    (car (cdr mobile))))

(define branch-length
  (lambda (branch)
    (car branch)))

(define branch-structure
  (lambda (branch)
    (car (cdr branch))))

(define total-weight
  (lambda (mobile)
    (+ (branch-weight (left-branch mobile))
       (branch-weight (right-branch mobile)))))

(define branch-weight
  (lambda (branch)
    ((lambda (structure)
       (if (pair? structure)
           (total-weight structure)
           structure))
     (branch-structure branch))))


(define branch1 (make-branch 1 10))
(define branch2 (make-branch 2 20))

(define mobile1 (make-mobile branch1 branch2))

(define branch3 (make-branch 1 mobile1))
(define branch4 (make-branch 2 mobile1))

(define mobile2 (make-mobile branch3 branch4))

(begin (newline)
       (display branch1)
       (newline)
       (display branch2)
       (newline)
       (display mobile1)       
       (newline)
       (display (total-weight mobile1))
       (newline)
       (display branch3)
       (newline)
       (display branch4)
       (newline)
       (display mobile2)
       (newline)
       (display (total-weight mobile2))
       (newline))

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

$ kscheme  < sample29_b.scm
In : Out: make-mobile
;(total-pushes = 3 maximum-depth = 3)
In : Out: make-branch
;(total-pushes = 3 maximum-depth = 3)
In : Out: left-branch
;(total-pushes = 3 maximum-depth = 3)
In : Out: right-branch
;(total-pushes = 3 maximum-depth = 3)
In : Out: branch-length
;(total-pushes = 3 maximum-depth = 3)
In : Out: branch-structure
;(total-pushes = 3 maximum-depth = 3)
In : Out: total-weight
;(total-pushes = 3 maximum-depth = 3)
In : Out: branch-weight
;(total-pushes = 3 maximum-depth = 3)
In : Out: branch1
;(total-pushes = 13 maximum-depth = 7)
In : Out: branch2
;(total-pushes = 13 maximum-depth = 7)
In : Out: mobile1
;(total-pushes = 13 maximum-depth = 7)
In : Out: branch3
;(total-pushes = 13 maximum-depth = 7)
In : Out: branch4
;(total-pushes = 13 maximum-depth = 7)
In : Out: mobile2
;(total-pushes = 13 maximum-depth = 7)
In : 
(1 10)
(2 20)
((1 10) (2 20))
30
(1 ((1 10) (2 20)))
(2 ((1 10) (2 20)))
((1 ((1 10) (2 20))) (2 ((1 10) (2 20))))
60
Out: ;undefined
;(total-pushes = 262 maximum-depth = 19)
In : $

0 コメント:

コメントを投稿