計算機プログラムの構造と解釈[第2版]
(翔泳社)
ハロルド エイブルソン (著) ジュリー サスマン (著)
ジェラルド・ジェイ サスマン (著)
Harold Abelson (原著) Julie Sussman (原著)
Gerald Jay Sussman (原著) 和田 英一 (翻訳)
開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Scheme (プログラミング言語)
- Gauche (処理系)
計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の3(標準部品化力、オブジェクトおよび状態)、3.3(可変データでのモデル化)、3.3.1(可変リスト構造)、共有と同一、問題 3.19.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
問題 3.19.
コード(BBEdit, Emacs)
sample3_19.scm
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
(define (cycle? x)
(define (iter a b)
(cond ((not (pair? a)) #f)
((memq a b) #t)
(else
(let ((c (cons a b)))
(or (iter (car a) c)
(iter (cdr a) c))))))
(iter x '()))
(define (last-pair x)
(if (null? (cdr x))
x
(last-pair (cdr x))))
(define (make-cycle x)
(set-cdr! (last-pair x) x)
x)
;; 循環する
(define z1 (make-cycle (list 'a 'b 'c)))
;; 循環しない
(define z2 '(a b a b a))
(print (cycle? z1)) ; #t
(print (cycle? z2)) ; #f
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ ./sample3_19.scm #t #f $
0 コメント:
コメントを投稿