learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-17.scm (1652B)


      1 (define-library (sicp solutions chapter-3 exercise-17)
      2   (import (scheme base))
      3   (export count-pairs)
      4 
      5   (begin
      6     (define (count-pairs x)
      7       (define (count-pairs' x known-pairs)
      8         (cond
      9          ((null? x) (cons 0 known-pairs))
     10          ((pair? x)
     11           (if (memq x known-pairs)
     12               (let* ([left-side (count-pairs' (car x)
     13                                               known-pairs)]
     14                      [left-side-count (car left-side)]
     15                      [left-side-known-pairs (cdr left-side)]
     16                      [right-side (count-pairs' (cdr x)
     17                                                left-side-known-pairs)]
     18                      [right-side-count (car right-side)]
     19                      [right-side-known-pairs (cdr right-side)])
     20                 (cons (+ 0
     21                          left-side-count
     22                          right-side-count)
     23                       right-side-known-pairs))
     24               (let* ([left-side (count-pairs' (car x)
     25                                               (cons x known-pairs))]
     26                      [left-side-count (car left-side)]
     27                      [left-side-known-pairs (cdr left-side)]
     28                      [right-side (count-pairs' (cdr x)
     29                                                left-side-known-pairs)]
     30                      [right-side-count (car right-side)]
     31                      [right-side-known-pairs (cdr right-side)])
     32                 (cons (+ 1
     33                          left-side-count
     34                          right-side-count)
     35                       right-side-known-pairs))))
     36          (else (cons 0 known-pairs))))
     37 
     38       (car (count-pairs' x '())))))