(define (count-pairs x) (define visited-pairs '()) (define (pair-visited? pair pairs) (cond ((null? pairs) #f) ((eq? pair (car pairs)) #t) (else (pair-visited? pair (cdr pairs))))) (define (count x) (if (or (not (pair? x)) (pair-visited? x visited-pairs)) 0 (begin (set! visited-pairs (cons x visited-pairs)) (+ (count (car x)) (count (cdr x)) 1)))) (count x)) ; Just DFS graph traversal ; 1 ]=> (define p3 (cons 'a (cons 'b (cons 'c '())))) ; ; ;Value: p3 ; ; 1 ]=> (count-pairs p3) ; ; ;Value: 3 ; ; 1 ]=> (define x (cons 'a '())) ; ; ;Value: x ; ; 1 ]=> (define p4 (cons x (cons 'b x))) ; ; ;Value: p4 ; ; 1 ]=> (count-pairs p4) ; ; ;Value: 3 ; ; 1 ]=> (define x (cons 'a '())) ; ; ;Value: x ; ; 1 ]=> (define y (cons x x)) ; ; ;Value: y ; ; 1 ]=> (define p7 (cons y y)) ; ; ;Value: p7 ; ; 1 ]=> (count-pairs p7) ; ; ;Value: 3 ; ; 1 ]=> (define x (cons 'c '())) ; ; ;Value: x ; ; 1 ]=> (define pinfinity (cons 'a (cons 'b x)) ; ) ; ; ;Value: pinfinity ; ; 1 ]=> (set-cdr! x pinfinity) ; ; ;Unspecified return value ; ; 1 ]=> (count-pairs pinfinity) ; ; ;Value: 3