乐正

Actions speak louder than words.

Sicp-ex2-40

问题

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

解答

练习2.40 (ex2-40.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
;; Happy hacking, Yuez - Emacs ♥ you!

(define (unique-pairs n)
  (flatmap (lambda (i)
             (map (lambda (j)
                    (list i j))
                  (enumerate-interval 1 (- i 1))))
           (enumerate-interval 1 n)))

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

测试

1
2
3
4
5
6
7
8
(unique-pairs 6)
;Value 28: ((2 1) (3 1) (3 2) (4 1) (4 2) (4 3) (5 1) (5 2) (5 3) (5 4) (6 1) (6 2) (6 3) (6 4) (6 5))

(prime-sum-pairs 6)
;Value 26: ((2 1 3) (3 2 5) (4 1 5) (4 3 7) (5 2 7) (6 1 7) (6 5 11))

(prime-sum-pairs 10)
;Value 27: ((2 1 3) (3 2 5) (4 1 5) (4 3 7) (5 2 7) (6 1 7) (6 5 11) (7 4 11) (7 6 13) (8 3 11) (8 5 13) (9 2 11) (9 4 13) (9 8 17) (10 1 11) (10 3 13) (10 7 17) (10 9 19))

draft

« sicp-ex2-39 sicp-ex2-41 »

Comments