【SICP练习】85 练习2.57

练习2.57

看到题目中的能处理任意项就赶紧这道题挺难的,同时也想到了前面学过但还没怎么用过的点参数。题目中要能求和还能求乘积。我们先来写求和的函数吧。

(define (make-sum a1 . a2)
(if (single-operand? a2)
   (let ((a2 (car a2)))
     (cond ((=number? a1 0) a2)
           ((=number? a2 0) a1)
           ((and (number? a1) (number? a2))
             (+ a1 a2))
            (else 
             (list ‘+ a1 a2))))
    (cons ‘+ (cons a1 a2))))

随后的sum?和addend等都不变,而augend则要做点修改了。

(define (augend s)
   (let ((tail-operand (cadd s)))
      (if (single-operand? tail-operand)
         (car tail-operand)
         (apply make-sum tail-operand))))

写好了加法就来写乘积了吧。

(define (make-sum m1 . m2)
(if (single-operand? m2)
   (let ((m2 (car m2)))
     (cond ((or (=number? m1 0) (=number? m2 0)) 0)
           ((=number? m1 1) m2)
           ((=number? m2 1) m1)
           ((and (number? m1) (number? m2))
            (* m1 m2))
           (else
            (list ‘* m1 m2))
   (cons ‘* (cons m1 m2))))

同样的,product?和multiplier都不变,而multiplicand则做些变化。

(define (multiplicand p)
    (let ((tail-operand (cddr p)))
       (if (single-operand? tail-operand)
          (car tail-operand)
           (apply make-product tail-operand))))

apply和map一样都是高阶函数,其作用是将make-product作用于tail-operand上。其余都代码都没有变动。现在就可以用make-product来接受任意个参数了。正因为要能够接受任意个参数,所以在multiplicand等上都使用了递归,在处理多操作符的时候,递归则可以将其不断的分为两个部分。宏观来讲,这也相当于cadr。



为使本文得到斧正和提问,转载请注明出处:
http://blog.csdn.net/nomasp


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

原文地址:https://www.cnblogs.com/NoMasp/p/4786134.html