2.41
练习 2.41 请写出一个过程,它能产生出所有小于等于给定整数n的正的相异整数i、j和k的有序三元组,使每个三元组的三个元之和等于给定的整数s。
首先,定义 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 (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))
(pairs 10)
(define (make-pair-sum pair)
(list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
(define (s-sum-pairs n s)
(map
make-pair-sum
(filter
(lambda (pair) (= (+ (car pair) (cadr pair)) s))
(pairs n)))
)
(s-sum-pairs 10 11)