2014年6月15日日曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の3(標準部品化力、オブジェクトおよび状態)、3.1(代入と局所状態)、3.1.2(代入を取り入れた利点)、問題 3.6.を解いてみる。

その他参考書籍

問題 3.6.

コード(BBEdit, Emacs)

sample3_6.scm

#!/usr/bin/env gosh
;; -*- coding:utf-8 -*-

(define (rand-update x)
  (modulo (+ x 1) 10))
          
(define rand
  (let ((x '()))
    (define (dispatch m)
      (cond ((eq? m 'generate)
             (if (eq? x '())
                 (error "Need to initialize -- RAND"
                        m)
                        
                 (begin (set! x (rand-update x))
                        x)))
            ((eq? m 'reset)
             (lambda (new-value)
               (set! x new-value)))
            (else
             (error
              "Need generate or reset -- RAND"
              m))))
    dispatch))

;; テスト
(define (test)
  (print "reset 5")
  ((rand 'reset) 5)
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print "reset 1")
  ((rand 'reset) 1)
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print "reset 5")
  ((rand 'reset) 5)
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print "reset 1")
  ((rand 'reset) 1)
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate))
  (print (rand 'generate)))

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

gosh> (load "./sample3_6.scm")
#t
gosh> (rand 'generate)
*** ERROR: Need to initialize -- RAND generate
Stack Trace:
_______________________________________
gosh> (test)
reset 5
6
7
8
9
0
reset 1
2
3
4
5
6
reset 5
6
7
8
9
0
reset 1
2
3
4
5
6
#<undef>
gosh> (exit)

0 コメント:

コメントを投稿