2013年7月9日火曜日

開発環境

計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の3(標準部品化力, オブジェクトおよび状態)、3.3(可変データでのモデル化)、3.3.1(可変リストの構造)、共有と同一の問題 3.16、問題 3.17、問題 3.18を解いてみる。

その他参考書籍

問題 3.16

3つの対で出来ているリスト構造で、count-pairsが3を返すものを表現する箱とポインタ図。

確認。

コード(BBEdit)

sample.scm

(define x (cons 'a (cons 'b (cons 'c '()))))

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

1 ]=> x

;Value 2: (a b c)

1 ]=> (count-pairs x)

;Value: 3

3つの対で出来ているリスト構造で、count-pairsが4を返すものを表現する箱とポインタ図。

確認。

コード(BBEdit)

sample.scm

(define z (cons 'c '()))
(define y (cons 'b z))
(define x (cons z y))

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

1 ]=> x

;Value 3: ((c) b c)

1 ]=> (count-pairs x)

;Value: 4

3つの対で出来ているリスト構造で、count-pairsが7を返すものを表現する箱とポインタ図。

確認。

コード(BBEdit)

sample.scm

(define z (cons 'a '()))
(define y (cons z z))
(define x (cons y y))

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

1 ]=> x

;Value 2: (((a) a) (a) a)

1 ]=> (count-pairs x)

;Value: 7

3つの対で出来ているリスト構造で、count-pairsが何も返さないものを表現する箱とポインタ図。

循環する。

コード(BBEdit)

sample.scm

(define x (cons 'a (cons 'b (cons 'c '()))))

(set-cdr! (last-pair x) x)

問題3.17

コード(BBEdit)

sample.scm

(define (last-pair x)
  (if (null? (cdr x))
      x
      (last-pair (cdr x))))

(define (count-pairs x)
  (define pairs '())
  (define (iter x)
    (if (or (not (pair? x)) (memq x pairs))
        0
        (begin (set! pairs (cons x pairs))
               (+ (iter (car x))
                  (iter (cdr x))
                  1))))
  (iter x))

(define x1 (cons 'a (cons 'b (cons 'c '()))))

(define z (cons 'c '()))
(define y (cons 'b z))
(define x2 (cons z y))

(define z (cons 'a '()))
(define y (cons z z))
(define x3 (cons y y))

(define x4 (cons 'a (cons 'b (cons 'c '()))))

(set-cdr! (last-pair x4) x4)

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

1 ]=> x1

;Value 2: (a b c)

1 ]=> (count-pairs x1)

;Value: 3

1 ]=> x2  

;Value 3: ((c) b c)

1 ]=> (count-pairs x2)

;Value: 3

1 ]=> x3   

;Value 4: (((a) a) (a) a)

1 ]=> (count-pairs x3)

;Value: 3

1 ]=> (count-pairs x4)

;Value: 3

問題3.18

コード(BBEdit)

sample.scm

(define (include-cycle? x)
  (define pairs '())
  (define (iter x)
    (if (not (pair? x))
        false
        (if (memq x pairs)
            true
            (begin (set! pairs (cons x pairs))
                   (iter (cdr x))))))
  (iter x))

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

1 ]=> (include-cycle? x1)

;Value: #f

1 ]=> (include-cycle? x2)

;Value: #f

1 ]=> (include-cycle? x3)

;Value: #f

1 ]=> (include-cycle? x4)

;Value: #t

0 コメント:

コメントを投稿