首页 > 其他 > 详细

1.3.1 (对过程的抽象)

时间:2017-11-24 23:32:11      阅读:249      评论:0      收藏:0      [点我收藏+]
(define (sum-integers a b)
  (if (> a b)
      0
      (+ a (sum-integers (+ a 1) b))))

(sum-integers 1 10)

(define (sum-cubes a b)
  (define (cube x)
    (* x x x))
  (if (> a b)
      0
      (+ (cube a) (sum-cubes (+ a 1) b))))

(sum-cubes 1 10)

(define (pi-sum a b)
  (if (> a b)
      0
      (+ (/ 1.0 (* a (+ a 2))) (pi-sum (+ a 4) b))))

(* 8 (pi-sum 1 1000000))

  对过程的抽象:

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

  填充:

(define (inc n)
  (+ n 1))

(define (cube n)
  (* n n n))

(define (sum-cubes a b)
  (sum cube a inc b))
(sum-cubes 1 10)

  

(define (inc n)
  (+ n 1))

(define (identity x) x)

(define (sum-integers a b)
  (sum identity a inc b))

(sum-integers 1 10)

  

(define (pi-next n)
  (+ n 4))

(define (pi-term x)
  (/ 1.0 (* x (+ x 2))))

(define (pi-sum a b)
  (sum pi-term a pi-next b))

(* 8 (pi-sum 1 10000))

  拓展:

(define (integral f a b dx)  ;积分
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2.0)) add-dx b)
     dx))

  (define (cube x) (* x x x))
  
(integral cube 0 1 0.0001)

  

1.3.1 (对过程的抽象)

原文:http://www.cnblogs.com/R4mble/p/7892680.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!