2015年10月19日月曜日

開発環境

  • 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.17.を解いてみる。

その他参考書籍

問題3.17.

コード(Emacs)

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

  (define (count-pairs pairs)
    (define counted-pairs (quote ()))
    (define (iter pairs)
      (cond ((not (pair? pairs)) 0)
            ((memq pairs counted-pairs) 0)
            (else (set! counted-pairs
                        (cons pairs counted-pairs))
                  (+ (iter (car pairs))
                     (iter (cdr pairs))
                     1))))
    (iter pairs))  
            

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

  (set-car! p (cddr p))
  (print (count-pairs p))
  (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))
  (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 sample17.scm
3
(1 2 3)
3
((3) 2 3)
3
(((3) 3) (3) 3)
3
$

0 コメント:

コメントを投稿