zoukankan      html  css  js  c++  java
  • 【SICP练习】59 练习2.29

    

    练习2.29

    这种题,还有之前的那个rectangle的题目,对于变量、函数等的命名简直要让人疯掉。先来写出题目中的left-branchright-branch吧。

    (define (left-branch mobile)

       (car mobile))

    (define (right-branch mobile)

       (cadr mobile))

    注意这里是cadr而不是cdr。对应的branch-lengthbranch-structure

    (define (branch-length branch)

       (car branch))

    (define (branch-structure branch)

       (cadr branch))

    a小题并不难,b小题中的total-weight也就是要求每部分branch-structure。而根据题目的意思,如果一个分支吊着另一个活动体,那么这个活动体的重量就是这个分支的重量,否则分支的structure就是这个分支的重量。而判断这个分支是不是还有其他活动体我们可以用pair?来判断。而总重量就是左右两部分的重量之和。

    (define (branch-weight branch)

       (if (pair? (branch-structure branch))

          (total-weight (branch-weight branch))

          (branch-structure branch)))

    (define (total-weight mobile)

       (+ (branch-weight (left-branch mobile))

          (branch-weight (right-branch mobile))))

    我们来测试一下结果。

    (define first-mobile (make-mobile(make-branch 20 10)

                                    (make-branch20 40)))

    (total-weight mobile)

    ;Value: 50

    (define second-mobile (make-mobile(make-branch 40 first-mobile)

                                        (make-branch 100 180)))

    ;Valeu: 230

    下面开始做c小题了。先来看看什么是力矩左杆的长度乘以吊在杆上的重量,等于这个活动体右边的同样乘积。这是活动体称为平衡的第一个条件,第二个条件则是要每个分支上吊着的子活动体也都平衡。于是我们可以定义如下的过程,我们先来定义力矩好了。

    (define (branch-force branch)

       (* (branch-length branch)

          (branch-weight branch)))

    (define (mobile-balance? mobile)

       (let ((left (left-branch mobile))

            (right (right-branch mobile)))

         (and (= (branch-force left)

                 (branch-force right))

              (branch-balance? left)

              (branch-balance? right))))

    (define (branch-balance? branch)

       (if (pair? (branch-structure branch))

          (mobile-balance? (branch-structure branch))

           #t))

    c小题我们也做完了,下面我们来乘胜追击完成最后一个小题好了。d小题将原先的list改成了cons。因此一开始所说的在right-branchbranch-structure要用cadr而不能用cdr,但是在这里用cdr就是正确的了。

    (define (left-branch mobile)

       (car mobile))

    (define (right-branch mobile)

       (cdr mobile))

     (define (branch-length branch)

       (car branch))

    (define (branch-structure branch)

       (cdr branch))

    是不是感觉很神奇呢?那就来测试吧。

    (define third-mobile (make-mobile(make-branch 20 25)

                                     (make-branch30 40)))

    ;Value: third-mobile

    third-mobile

    ;Value: ( ( 20 . 25) 30 . 40 )

    注意第二章所讲的数据抽象,因此前面的mobile-balance?在这里也是一样可以用的。

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

  • 相关阅读:
    关于正则表达式
    hashilib模块和hmac模块
    PyYAML模块和ConfigParser模块
    xml处理模块
    shutil模块(文件,文件夹,压缩包处理)
    十四、浏览器检测
    十三、BOM
    十二、匿名函数和闭包
    并发,并行,同步,异步的区别
    java中常见的类,接口,包,异常
  • 原文地址:https://www.cnblogs.com/NoMasp/p/4786160.html
Copyright © 2011-2022 走看看