2015年10月18日日曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs(Text Editor)
  • Scheme (プログラミング言語)
  • kscheme (github) (処理系)

計算機プログラムの構造と解釈[第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.16.を解いてみる。

その他参考書籍

問題3.16.

コード(Emacs)

(begin
  (define (print obj)
    (display obj)
    (newline))

  (define (count-pairs x)
    (if (not (pair? x))
        0
        (+ (count-pairs (car x))
           (count-pairs (cdr x))
           1)))

  (define p (cons 1 (cons 2 (cons 3 (quote ())))))
  (print (count-pairs p))              ; 3
  (print p)

  (set-car! p (cddr p))
  (print (count-pairs p))               ; 4
  (print p)

  (define p (cons 1 (cons 2 (cons 3 (quote ())))))
  (set-car! (cdr p) (cddr p))
  (set-car! p (cdr p))
  (print (count-pairs p))               ; 7
  (print p)

  (define p (cons 1 (cons 2 (cons 3 (quote ())))))
  (set-cdr! (cddr p) p)
  (print (count-pairs p)))              ; 循環

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

$ ./kscheme sample16.scm
3
(1 2 3)
4
((3) 2 3)
7
(((3) 3) (3) 3)
  C-c C-c
$

0 コメント:

コメントを投稿