開発環境
- 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.1(データ抽象入門)、2.1.3(データとは何か)、問題 2.5.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
問題 2.5.
コード(BBEdit, Emacs)
sample.scm
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
;; a、bは非負の整数
;; a、bの対
(define (cons a b)
(define (iter b n result)
(if (= n 0)
result
(iter b
(- n 1)
(* b result))))
(* (iter 2 a 1)
(iter 3 b 1)))
(define (car x)
(define (iter n count)
(if (> (remainder n
2)
0)
count
(iter (/ n 2)
(+ count 1))))
(iter x 0))
(define (cdr x)
(define (iter n count)
(if (> (remainder n
3)
0)
count
(iter (/ n 3)
(+ count 1))))
(iter x 0))
;; テスト
(for-each (lambda (p)
(print p ", " (car p) ", " (cdr p)))
(list (cons 0 0)
(cons 0 1)
(cons 1 0)
(cons 1 1)
(cons 5 6)))
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ ./sample.scm 1, 0, 0 3, 0, 1 2, 1, 0 6, 1, 1 23328, 5, 6 $
0 コメント:
コメントを投稿