Created
May 24, 2021 06:23
-
-
Save yanfeng42/746d3038d3cd40ecd30e934657c0fcb1 to your computer and use it in GitHub Desktop.
sicp 1.33 带filter的accumulate.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (filtered-accumulate combiner null-value term a next b filter?) | |
(if (> a b) | |
null-value | |
(combiner (if (filter? a) (term a) null-value) | |
(filtered-accumulate combiner null-value term (next a) next b filter?) | |
) | |
) | |
) | |
(define (filtered-sum term a next b filter?) | |
(filtered-accumulate + 0 term a next b filter?) | |
) | |
(define (prime-sum a b) | |
(define (term x) x) | |
(define (next a) (+ a 1)) | |
; prime? 前面练习已实现.(1 不是素数.) | |
(filtered-sum term a next b prime?) | |
) | |
; 6 | |
(prime-sum 1 3) | |
; 在数论中,如果两个或两个以上的整数的最大公约数是 1,则称它们为互质[2]. | |
(define (filtered-sum term a next b filter?) | |
(filtered-accumulate + 0 term a next b filter?) | |
) | |
(define (prime-product n) | |
(define (term x) x) | |
(define (next a) (+ a 1)) | |
(define (filter? x) (= (gcd n x) 1)) | |
(filtered-accumulate * 1 term 2 next (- n 1) filter?) | |
) | |
; 24 | |
(prime-product 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(combiner (if (filter? a) (term a) null-value) (filtered-accumulate combiner null-value term (next a) next b filter?) )
比较特殊的可能是这句. 基础语法糖熟悉以后, 越来越倾向于 单行书写了. 的确精简很多.