sicp练习1.20 gcd过程 应用序 正则序 remainder次数

(define (gcd a b remainder-count)
  (if(= b 0)
     (begin (display "\nremainder count: ")
            (display remainder-count)
            (display "\n gcd result:")
            (display a)
            (display "\n")
            a)
     (gcd b (remainder a b) (+ remainder-count 1))))

(gcd 12 9 0)
;(gcd 12 28 0)

(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

(define (gcd-new-if a b remainder-count)
  (new-if (= b 0)
     (begin (display "\nremainder count: ")
            (display remainder-count)
            (display "\n gcd result:")
            (display a)
            (display "\n")
            a
            )
     (gcd-new-if b (remainder a b) (+ remainder-count 1))))

(gcd-new-if 12 9 0)
;(new-if (> 1 2) (begin (display "1") (display "1") )(display "2"))

  以上gcd函数自动记录remainder调用次数。(gcd 12 9 0)调用remainder次数为2次。

if的scheme运算是正则运算,不管怎么样子都是先对谓词求值,然后分支运算。

要使得scheme运算为应用序,则需要使用new-if,自己定义个函数来代替if,由于new-if是自定义的函数,则使用应用序先对其参数顺序求值。因此会导致gcd-new-if 循环调用而产生死循环,并且由于remainder的存在,在循环调用的过程中,remainder a b 的参数b为0时,则发生错误,即求余运算中的除数为0,导致错误。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值