2.40

练习 2.40 请定义过程unique-pairs,给它整数n,它产生出序对(i, j),其中1j<in 1 \le j < i \le n 。请用unique-pairs去简化上面的prime-sum-pairs的定义。


首先,定义 accumulate

 
(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence))) 
      )
  )
x
 
#<undef>

然后,定义 flatmap

 
(define (flatmap proc seq)
  (accumulate append '()  (map proc seq)))
 
#<undef>
 
(define (enumerate-interval low high)
  (if (> low high)
      '()
      (cons low (enumerate-interval (+ low 1) high))))
(define (unique-pairs n)
  (define interval (enumerate-interval 1 n))
  (flatmap  
   (lambda (x) 
     (filter 
      (lambda (lst) (< (car lst) (cadr lst)))
      (map 
       (lambda (y) (list x y)) 
       (remove x interval))))
   interval))
(unique-pairs 10)
 
((1 2) (1 3) (1 4) (1 5) (1 6) (1 7) (1 8) (1 9) (1 10) (2 3) (2 4) (2 5) (2 6) (2 7) (2 8) (2 9) (2 10) (3 4) (3 5) (3 6) (3 7) (3 8) (3 9) (3 10) (4 5) (4 6) (4 7) (4 8) (4 9) (4 10) (5 6) (5 7) (5 8) (5 9) (5 10) (6 7) (6 8) (6 9) (6 10) (7 8) (7 9) (7 10) (8 9) (8 10) (9 10))
 
(define (remainder a b) (cond ((< (- a b) b) (- a b))
                              (else (remainder (- a b) b))
                              ))
(define (smallest-divisor n)
  (find-divisor n 2))
(define (square x) (* x x))
(define (find-divisor n test-divisor)
  (cond ((> (square test-divisor) n) n)
        ((divides? test-divisor n) test-divisor)
        (else (find-divisor n (+ test-divisor 1)))))
(define (divides? x y)
  (= (remainder y x) 0))
(define (prime? x) (= x (smallest-divisor x)))
 
#<undef>
 
(define (make-pair-sum pair)
  (list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
(define (prime-sum? pair)
  (prime? (+ (car pair) (cadr pair))))
(define (prime-sum-pairs n)
  (map 
   make-pair-sum 
   (filter 
    prime-sum? 
    (unique-pairs n)))
  )
(prime-sum-pairs 10)
 
((1 2 3) (1 4 5) (1 6 7) (1 10 11) (2 3 5) (2 5 7) (2 9 11) (3 4 7) (3 8 11) (3 10 13) (4 7 11) (4 9 13) (5 6 11) (5 8 13) (6 7 13) (7 10 17) (8 9 17) (9 10 19))

results matching ""

    No results matching ""