zoukankan      html  css  js  c++  java
  • 【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来构造一个求ab之间所有素数的和了。就像上一道题中将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语言中的指针,灵活运用则威力强大。

    版权声明:本文为 NoMasp柯于旺 原创文章,如需转载请联系本人。

  • 相关阅读:
    网络编程
    模块
    内置函数
    函数应用
    万能参数
    函数
    爬虫
    算法
    Flask
    linux
  • 原文地址:https://www.cnblogs.com/NoMasp/p/4786203.html
Copyright © 2011-2022 走看看