2014年6月27日金曜日

開発環境

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

その他参考書籍

問題 3.18.

コード(BBEdit, Emacs)

sample3_18.scm

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

(define (loop? x)
  (let ((y '()))
    (define (iter z)
      (if (not (pair? z))
          #f
          (begin (set! y (cons z y))
                 (let ((a (cdr z)))
                   (if (memq a y)
                       #t
                       (iter a))))))
    (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))

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

gosh> #t
gosh> (loop? z1)
#t
gosh> z1
#0=(a b c . #0#)
gosh> (loop? z2)
#f
gosh> z2
(a b a b a)
gosh> 
$

0 コメント:

コメントを投稿