享受代码,享受人生

SOA is an integration solution. SOA is message oriented first.
The Key character of SOA is loosely coupled. SOA is enriched
by creating composite apps.
posts - 98, comments - 2402, trackbacks - 162, articles - 45
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

SICP 习题1.6

Posted on 2006-05-01 23:54 idior 阅读(1464) 评论(4) 编辑 收藏

(define (new-if pre thenc elsec)
       (cond (pre thenc) (else elsec)))

(define (squa-it guess x)
      (new-if (goodenough? guess x)
          guess
          (squa-it(improve guess x) x)
          ))

(define (improve guess x)
      (avg guess (/ x guess)))

(define (avg x y) (/ (+ x y) 2))

(define (goodenough? guess x)
     (< (abs (- (square  guess) x)) 0.001))
(define (sqrt x)
        (squa-it 1 x))
(define (square x)
         (* x x))

其中可以发现由于使用了自定义的new-if procedure 按照scheme的applicative-order evaluation方式,pre thenc elsec这三个表达式都要被计算,这样的话一旦在某个表达式中再次出现调用该new-if的表达式就陷入死循环。为了避免死循环,一个方法就是不出现递规,显然这不现实,因为很多计算方法都用到了递规的思想,还有一个办法就是可以在某些时候停止递规, 如果使用special form就可以不必计算所有表达式比如cond if. 比如上面的方法改写成下面这样就不会出问题了。

(define (squa-it guess x)
      (cond ((goodenough? guess x) guess)
            (else (squa-it(improve guess x) x))
          ))