【SICP练习】27 练习1.33



练习1.33

题目第二行描述,只组合起由给定范围得到的项里的那些满足特定条件的项,因此我们需要在这一版本的accumulate中添加一个need-filter?,这个新的谓词可以用来传递下面就要用到的prime?。

(define (filtered-accumulateneed-filter? combiner null-value term a next b)

(if (> a b)

  null-value

  (let ((other-term (filtered-accumulateneed-filter?

                                      combiner

                                      null-value

                                       term

                                       (nexta)

                                       b)))

       (if (need-filter? a)

               other-term

          (combiner (term a) other-term)))))

因此我们就可以通过accumulate来构造一个求a到b之间所有素数的和了。就像上一道题中将accumulate补充称product等一样,这里也是将抽象的filtered-accumulate添加一些固定的元素让它稍微”具体“点。a小题的函数也就出来了。

(define(accumulate-prime-sum a b)

   (filtered-accumulate prime? + 0 (lambda (x)x) a (lambda (x) (+ x 1)) b))

编译这段函数的前提是你已经将prime?加载上来了。

其实解答b小题就是要写出一个能够判断互素的谓词,这里定为a-prime-to-b?。

(define (a-prime-to-b? a b)

   (and (< a b) (= 1 (gcd a b))))

同样的,在这里也应该要将gcd函数加载上来。

类似于前面将need-to-filter?替换成prime?的过程,这里是用的谓词a-prime-to-b?。

(define (product-of –prime-accumulaten)

  (filtered-accumulate (lambda (x) (a-prime-to-b?x n))

                      *

                      1

                      (lambda (x) x)

                      1

                      (lambda (x) (+ x 1))

                      n))

作为初学者,还是多做点实践好了,再来写出迭代版本的filtered-accumulate

我就不再将我对比的过程写下来了,大家可以翻到前面看看。

(define (filtered-accumulateneed-to-filter? combiner null-value term a next b)

   (define (filtered-accumulate-iter a other)

        (cond ((> a b) other)

              ((need-to-filter? a)

               (filtered-accumulate-iter (nexta) (combiner (term a) other)))

              (else

               (filtered-accumulate-iter (nexta) other))))

  (filtered-accumulate a null-value))

这道题我们就这样写完了,接下来我们会开始着重学习lambda了。虽然前面用过不少,但要想灵活运用lambda则比较难了。个人理解,lambda就像是C语言中的指针,灵活运用则威力强大。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值