练习 1.18

结合 练习 1.16练习 1.17 的技术,写出使用对数步数迭代计算出乘积的乘法函数:

;;; 18.scm

(load "17-double-and-halve.scm")

(define (multi a b)
    (multi-iter a b 0))

(define (multi-iter a b product)
    (cond ((= b 0)
            product)
          ((even? b)
            (multi-iter (double a)
                        (halve b)
                        product))
          ((odd? b)
            (multi-iter a
                        (- b 1)
                        (+ a product)))))

乘法函数重用了 练习 1.17 中的 doublehalve 函数,并且为了避免和内置的 * 函数混淆,我们将乘法函数的名字改为 multi

测试:

1 ]=> (load "18.scm")

;Loading "18.scm"...
;  Loading "17-double-and-halve.scm"... done
;... done
;Value: multi-iter

1 ]=> (multi 2 2)

;Value: 4

1 ]=> (multi 3 3)

;Value: 9

1 ]=> (multi 3 4)

;Value: 12

讨论

blog comments powered by Disqus