2016年12月24日土曜日

Scheme - 標準部品化力、オブジェクト及び状態(可変データでのモデル化(可変リスト構造(共有と同一)))

その他参考書籍

コード(Emacs)

```(begin
(define port (current-output-port))
(define (p x) (display x port) (display #\newline port))
(define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(+ (count-pairs (cdr x))
1))))

(define (memq x list)
(if (null? list)
#f
(if (eq? x (car list))
list
(memq x (cdr list)))))
(p "3.16")
(define three (list 1 2 3))
(define four (list 1 2 3))
(define seven (list 1 2 3))
(define cycle (list 1 2 3))

(p (count-pairs three))
(p (count-pairs four))
(p (count-pairs seven))

(display #\newline port)

(set-car! four (cdr (cdr four)))
(set-car! seven (cdr seven))
(set-car! (cdr seven) (cdr (cdr seven)))
(set-cdr! cycle cycle)

(p (count-pairs three))
(p (count-pairs four))
(p (count-pairs seven))
(display #\newline port)

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

(p (count-pairs-1 three))
(p (count-pairs-1 four))
(p (count-pairs-1 seven))

(display #\newline port)

(p "3.18, 3.19")

(define (cycle? list)
(define (iter x y)
(if (null? y)
#f
(if (eq? x y)
#t
(if (and (not (null? (cdr y))))
(iter (cdr x) (cdr (cdr y)))
#f))))
(if (null? list)
#f
(iter list (cdr list))))

(p (cycle? three))
(p (cycle? four))
(p (cycle? seven))
(p (cycle? cycle))

'done)
```

```\$ gmake -s sample && ./sample
=> compiled
3.16
3
3
3

3
4
7

3.17
3
3
3

3.18, 3.19
#false
#false
#false
#true
=> done
\$
```