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

然后,定义 flatmap

(define (flatmap proc seq)
    (accumulate append '()  (map proc seq)))
(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)
(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)))
(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)

results matching ""

    No results matching ""