练习1.31-练习1.34

15 篇文章 0 订阅

最近对于Lisp的强大和高深还是深有体会的,可以将函数作为参数进行调用,这样在很大的程度上可以提高函数的抽象性,即将具有公共模式的函数进行抽象。例如在SICP中,首先将累加和的过程进行了抽象,然后在累加和的基础上抽象出了累乘积,进而又发现了累加和与累乘积的共同点,进一步抽象成了一个叫做accumulate的函数,这个函数的是这样的

(accumulate combiner null-value term a next b)

其中combiner为被组合项的组合方式,例如在累加和中可以是“+”,在累乘积中可以是“*”,null-value为默认值,在累加和中为0累乘积中为1,term为函数f,例如在求cube的积分时,f为cube,a为初始值,next为下一次取得值,b为取值的上限。

最后在accumulate函数的基础上加上了对数据的filter使得整个过程更加抽象更加一般。

1.练习1.31

a)

(define (product-recur term a next b)
  (if (> a b)
      1
      (* (term a)
	 (product-recur term (next a) next b))))

(define (factorial-recur n)
  (define (self n)
    n)
  (define (plus-1 n)
    (+ n 1))
  (if (= n 0)
      1
      (product-recur self 1 plus-1 n)))

(define (pi-recur n)
  (define (even? n)
    (= (remainder n 2) 0))
  (define (item n)
    (if (even? n)
	(/ (+ 2 n) (+ 1 n))
	(/ (+ 1 n) (+ 2 n))))
  (define (next-1 n)
    (+ n 1.0))
  (* 4.0
     (product-recur item 1.0 next-1 n)))

b)

(define (product-iter term a next b)
  (define (iter a result)
    (if (> a b)
	result
	(iter (next a) (* (term a) result))))
  (iter a 1))

2.练习1.32

a)

(define  (accumulate combiner null-value term a next b)
  (if (> a b)
      null-value
      (combiner (term a)
		(accumulate combiner null-value term (next a) next b))))

(define (sum-accumulate term a next b)
  (accumulate + 0 term a next b))

(define (product-accumulate term a next b)
  (accumulate-iter * 1 term a next b))

b)

(define  (accumulate-iter combiner null-value term a next b)
  (define (iter a result)
    (if (> a b)
	result
	(iter (next a) (combiner result (term a)))))
  (iter a null-value))

3.练习1.33

(define (filtered-accumulate filter combiner null-value term a next b)
  (define (iter a result)
    (cond ((> a b) result)
	  ((filter a) (iter (next a) (combiner (term a) result)))
	  (else (iter (next a) result))))
  (iter a null-value))

a)

(define (prime-sum a b)
  (define (next-1 a)
    (+ a 1))
  (define (self a)
    a)
  (filtered-accumulate prime? + 0 self a next-1 b))

b)

(define (GCD-1-product n)
  (define (GCD-1-n? a)
    (= (GCD a n) 1))
  (define (next-1 a)
    (+ a 1))
  (define (self a)
    a)
  (filtered-accumulate GCD-1-n? * 1 self 1 next-1 (- n 1)))

4.练习1.34

可以这么解释(f f)->(f 2)->(2 2),最后由于2这个函数没有定义,所以报错结束。


网上发现了这个点击打开链接,很不错,貌似是一些人做的项目,目的是解答SICP上的所有题,貌似很久没有更新了,但以后做了题还是可以和这个上面已有的解答对对了。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值