书本 83 页的第一段代码其实就是 unique-pairs
的定义:
(accumulate append
'()
(map (lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate 1 n)))
不过书本给出的这段代码并没有使用 flatmap
函数,我们将那这段代码改成使用 flatmap
的版本就行了:
;;; 40-unique-pairs.scm
(load "p78-enumerate-interval.scm")
(load "p83-flatmap.scm")
(define (unique-pairs n)
(flatmap (lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))
测试:
1 ]=> (load "40-unique-pairs.scm")
;Loading "40-unique-pairs.scm"...
; Loading "p78-enumerate-interval.scm"... done
; Loading "p83-flatmap.scm"...
; Loading "p78-accumulate.scm"... done
; ... done
;... done
;Value: unique-pairs
1 ]=> (unique-pairs 4)
;Value 12: ((2 1) (3 1) (3 2) (4 1) (4 2) (4 3))
1 ]=> (unique-pairs 6)
;Value 13: ((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))
unique-pairs
重定义 prime-sum-pairs
¶;;; 40-prime-sum-pairs.scm
(load "40-unique-pairs.scm")
(load "p83-prime-sum.scm")
(load "p83-make-pair-sum.scm")
(define (prime-sum-pairs n)
(map make-pair-sum
(filter prime-sum? (unique-pairs n))))
测试:
1 ]=> (load "40-prime-sum-pairs.scm")
;Loading "40-prime-sum-pairs.scm"...
; Loading "40-unique-pairs.scm"...
; Loading "p78-enumerate-interval.scm"... done
; Loading "p83-flatmap.scm"...
; Loading "p78-accumulate.scm"... done
; ... done
; ... done
; Loading "p83-prime-sum.scm"...
; Loading "p33-prime.scm"...
; Loading "p33-smallest-divisor.scm"... done
; ... done
; ... done
; Loading "p83-make-pair-sum.scm"... done
;... done
;Value: prime-sum-pairs
1 ]=> (prime-sum-pairs 6)
;Value 11: ((2 1 3) (3 2 5) (4 1 5) (4 3 7) (5 2 7) (6 1 7) (6 5 11))