SICP Exercise 2.40

Question

Define a procedure unique-pairs that, given an integer \(n\), generates the sequence of pairs \((i,j)\) with \(1\le j<i\le n\). Use unique-pairs to simplify the definition of prime-sum-pairs given above.

Answer

There really isn’t much to this, the answer is basically in the text. The only difference is now we are outsourcing part of prime-sum-pairs into a helper procedure. I am also giving a definition of enumerate-interval here since it’s not in the book. Note that this does require starting at 2 as a lower bound for i to avoid an infinite loop. It still works since (1,1) is not a valid pair anyways.

(define (enumerate-interval lower upper)
  (if (equal? lower upper)
      (list upper)
      (cons lower (enumerate-interval (inc lower) upper))))

(define (unique-pairs n)
  (flatmap
   append
   (map (λ (i)
          (map (λ (j)
                 (list j i))
               (enumerate-interval 1 (- i 1))))
        (enumerate-interval 2 n))))

(define (prime-sum-pairs n)
  (map make-pair-sum
       (filter
        prime-sum?
        (unique-pairs n))))

; testing:
(prime-sum-pairs 6)

Results:

((1 2 3) (2 3 5) (1 4 5) (3 4 7) (2 5 7) (1 6 7) (5 6 11))