Exercise 3.17.  Devise a correct version of the count-pairs  procedure 
of exercise 3.16  that returns the number of distinct pairs in any 
structure. (Hint: Traverse the structure, maintaining an auxiliary data 
structure that is used to keep track of which pairs have already been 
counted.)

————————————————————————————————————————————————————————————————————————

(define (count-pairs x)
  (define (count x seen)
    (if (or (null? x) (memq x seen))
        0
        (+ (count (car x) (cons x seen))
           (count (cdr x) (cons x seen))
           1))))
  (count x '()))

As discussed on IRC, this first attempt is wrong, since the elements 
that appear in both the car and cdr of a given element will be counted 
twice.  A corrected solution:

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