開発環境
- 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))の2(データによる抽象の構築)、2.2(階層データ構造と閉包性)、2.2.2(階層構造)、問題 2.29-a, b.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
問題 2.29-a, b.
コード(BBEdit, Emacs)
sample.scm
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
;; 二進モービル
;; 構成子
(define (make-mobile left right)
(list left right))
(define (make-branch length structure)
(list length structure))
;; 選択子
(define (left-branch mobile)
(car mobile))
(define (right-branch mobile)
(car (cdr mobile)))
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(cadr branch))
(define (total-weight mobile)
(define (branch-weight branch weight)
((lambda (structure)
(if (number? structure)
(+ weight structure)
(+ weight
(total-weight structure))))
(branch-structure branch)))
(+ (branch-weight (left-branch mobile) 0)
(branch-weight (right-branch mobile) 0)))
(define b1 (make-branch 1 2))
(define b2 (make-branch 3 4))
(define m1 (make-mobile b1 b2))
(define b3 (make-branch 5 m1))
(define m2 (make-mobile b1 b3))
(define m3 (make-mobile b2 b3))
(print "二進モービルと重量")
(for-each (lambda (mobile)
(print mobile ": " (total-weight mobile)))
(list m1 m2 m3))
(print "枝")
(for-each print
(list b1 b2 b3))
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ ./sample.scm 二進モービルと重量 ((1 2) (3 4)): 6 ((1 2) (5 ((1 2) (3 4)))): 8 ((3 4) (5 ((1 2) (3 4)))): 10 枝 (1 2) (3 4) (5 ((1 2) (3 4))) $
0 コメント:
コメントを投稿