;计算整数的累加和
(define (sum-integers a b)
(if (> a b)
0
(+ a (sum-integers (+ a 1) b))
)
)
;计算整数的累加立方和
(define (sum-cubes a b)
(if (> a b)
0
(+ (* a a a) (sum-cubes (+ a 1) b))
)
)
;计算收敛到8/pai
(define (sum-pi a b)
(if (> a b)
0
(+ (/ 1.0 (* a (+ a 2))) (sum-pi (+ a 4) b))
)
)
;抽象出通用处理过程,具体的处理用参数传递
(define (sum a b term next)
(if (> a b)
0
(+ (term a) (sum (next a) b term next))
)
)
;重新定义以上三种方法
(define (sum-integers a b)
(define (identity x) x)
(define (next x) (+ x 1))
(sum a b identity next)
)
(define (sum-cubes a b)
(define (identity x) (* x x x))
(define (next x) (+ x 1))
(sum a b identity next)
)
(define (sum-pi a b)
(define (identity x) (/ 1.0 (* x (+ x 2))))
(define (next x) (+ x 4))
(sum a b identity next)
)
;求定积分的一种方法
(define (integral f a b dx)
(* (sum-integral f a b dx) dx)
)
(define (sum-integral f a b dx)
(if (> a b)
0
(+ (f (+ a (/ dx 2.0))) (sum-integral f (+ a dx) b dx))
)
)
;也可以用以上的抽象方法描述
(define (sum-integral f a b dx)
(define (identity a) (f (+ a (/ dx 2.0))))
(define (next a) (+ a dx))
(sum a b identity next)
)
;所以抽象业务过程的关键在于寻找变量和不变量,由不变量构成业务逻辑,具体的变量由参数传递。
;普通函数的抽象是对数据的抽象,这里的函数的抽象是对行为抽象
一种抽象业务逻辑的方法
最新推荐文章于 2024-06-18 22:06:17 发布