sicp每日一题[1.32]

Exercise 1.32

a. Show that sum and product (Exercise 1.31) are both special cases of a still more general notion called a c c u m u l a t e accumulate accumulate that combines a collection of terms, using some general accumulation function:
(accumulate combiner null-value term a next b)
a c c u m u l a t e accumulate accumulate takes as arguments the same term and range specifications as s u m sum sum and p r o d u c t product product,together with a c o m b i n e r combiner combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a n u l l − v a l u e null-value nullvalue that specifies what base value to use when the terms run out. Write a c c u m u l a t e accumulate accumulate and show how s u m sum sum and p r o d u c t product product can both be defined as simple calls to a c c u m u l a t e accumulate accumulate.

b. If your a c c u m u l a t e accumulate accumulate procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.

answer :

  • a
; use recursive
(define (accumulate-recur combiner null-value term a next b)
  (if (> a b)
      null-value
      (combiner (term a)
                (accumulate-recur combiner null-value term (next a) next b))))

; computes the summation of two numbers
(define (sum a b)
  (accumulate-recur + 0 identity a inc b))

; computers the production of two numbers
(define (product a b)
  (accumulate-recur * 1 identity a inc b))

(sum 3 5)
(product 3 5)
  • b
; use iter
(define (accumulate-iter combiner null-value term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (combiner (term a) result))))
  (iter a null-value))

; computes the summation of two numbers
(define (sum a b)
  (accumulate-iter + 0 identity a inc b))

; computers the production of two numbers
(define (product a b)
  (accumulate-iter * 1 identity a inc b))

(sum 3 5)
(product 3 5)
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值