読書会

昨晩実施。久々でした。いいカンジで 3.3.1 節を読み進めてましたが問題 3.17 の次の問題でハマった模様。わしは 3.17 の解があまり理解できてなかったので、ちょい検討してみたんですが、もの凄いイキオいでハマりました。

とりあえず

検討中のソレが以下。

(use srfi-1)
(define (append! x y)
  (set-cdr! (last-pair x) y)
  x)
(define (last-pair x)
  (if (null? (cdr x))
      x
      (last-pair (cdr x))))
(define (in? x history)
  (not (null? (filter (lambda (x_) (eq? x x_)) history))))
(define (count-pairs x)
  (let ((history (cons '() '())))
    (let loop ((x x))
	 (if (or (not (pair? x)) (in? x history))
	     0
	   (begin
            (append! history (list x))
	    (+ (loop (car x))
	       (loop (cdr x))
	       1))))))

あら? 動いたぞ。あ、検討中のは以下だったのか。

(define (count-pairs x)
  (let loop ((x x) (history (cons '() '())))
    (if (or (not (pair? x)) (in? x history))
        0
        (begin
          (append! history (list x))
          (+ (loop (car x) history)
             (loop (cdr x) history)
             1)))))

ぬおー。たったこれだけの原因? まぁ、ポカと言えばポカですな。。。