sicp每日一题[1.30-1.31]

Exercise 1.31

  • a. The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher order procedures.51 Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Show how to define factorial in terms of product. Also use product to compute approximations to π using the formula
    π 4 = 2 ⋅ 4 ⋅ 4 ⋅ 6 ⋅ 6 ⋅ 8... 3 ⋅ 3 ⋅ 5 ⋅ 5 ⋅ 7 ⋅ 7... \frac{\pi}4=\frac{2\cdot4\cdot4\cdot6\cdot6\cdot8...}{3\cdot3\cdot5\cdot5\cdot7\cdot7...} 4π=335577...244668...
  • b. If your product 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
(define (product-iter term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (* (term a) result))))
  (iter a 1))

(define (factorial n)
  (define (identity x) x)
  (product-iter identity 1 inc n))

(factorial 0)
(factorial 1)
(factorial 2)
(factorial 3)

> result
1
1
2
6
  • b
(define (product-recur term a next b)
  (if (> a b)
      1
      (* (term a)
         (product-recur term (next a) next b))))

(define (factorial n)
  (define (identity x) x)
  (product-recur identity 1 inc n))

(factorial 0)
(factorial 1)
(factorial 2)
(factorial 3)

> result
1
1
2
6
  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值