一种抽象业务逻辑的方法

;计算整数的累加和
(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)
)
;所以抽象业务过程的关键在于寻找变量和不变量,由不变量构成业务逻辑,具体的变量由参数传递。
;普通函数的抽象是对数据的抽象,这里的函数的抽象是对行为抽象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值