my attempt to do the exercises in sicp.

Thursday, July 17, 2008

sicp exercise 2.40



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

(define (accumulate op init seq)
  (cond ((null? seq) init)
        (else (op (car seq) (accumulate op init (cdr seq))))))

(define (enumerate-interval start end)
  (cond ((> start end) (list))
        (else (cons start (enumerate-interval (+ start 1) end)))))


(define (unique-pair n)
  (map
    (lambda (x)
      (map
        (lambda (y) (list y x))
        (enumerate-interval 1 (- x 1))))
    (enumerate-interval 1 n)))

(define (all-pairs n)
  (accumulate append (list) (unique-pair n)))

(display (all-pairs 5)) (newline)

No comments: