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.)

 


;; From scheme wiki
(define (count-pairs x)
(let ((encountered '()))
(define (helper x)
(if (or (not (pair? x)) (memq x encountered))
0
(begin
(set! encountered (cons x encountered))
(+
(helper (car x))
(helper (cdr x))
1))))
(helper x)))

view raw

s317.scm

hosted with ❤ by GitHub

 

 

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading