sicp-124-125

Posted on 2015-02-12 23:17:32 +0900 in SICP Lisp

1.16

#lang planet neil/sicp

 (define (square x) (* x x))

(define (fast-expt b n)
  (define (iter a b n)
    (cond ((= n 0) a)
          ((even? n) (iter a (square b) (/ n 2)))
          (else (iter (* a b) b (- n 1)))))
  (iter 1 b n))

1.18

(define (multi a b)
  (define (fast-multi-iter x y n)
    (cond ((= n 0) x)
          ((even? n) (fast-multi-iter x (double y) (/ n 2)))
          (else (fast-multi-iter (+ x y) y (- n 1)))))
  (fast-multi-iter 0 a b))

1.20

Applicative order:

gcd(206, 40)
gcd(40, remainder(206, 40)) ;1
gcd(6, remainder(40, 6))   ;2
gcd(4, remainder(6, 4))  ;3
gcd(2, remainder(4, 2))  ;4

For normal order, the remainder function is not calculated instantly. It is calculated when it is necessary. It is passed by as a delay item.

(gcd 206 40)
(gcd 40 (remainder 206 40))
->
(if (= (remainder 206 40) 0)
  40
  (gcd (remainder 206 40)
    (remainder 40 (remainder 206 40))))
->
(if (= (remainder 40 (remainder 206 40)) 0)
  (remainder 206 40)
  (gcd
    (remainder
      40
      (remainder 206 40))
    (remainder
      (remainder 206 40)
      (remainder
        40
        (remainder 206 40)))))
...
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | SICP 1.2.3 »

Hide Comments

comments powered by Disqus