Scheme中基本if表达式的修改.为什么会陷入无限循环? [英] Modification of the basic if expression in Scheme. Why does it go into an infinite loop?

查看:102
本文介绍了Scheme中基本if表达式的修改.为什么会陷入无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scheme中,我将基本的'if'命令修改为:

In Scheme, I modified the basic 'if' command as:

(define (modified-if predicate then-clause else-clause)
  (if predicate
      then-clause
      else-clause))

然后我使用if的修改版本定义了一个简单的阶乘生成程序:

And then I defined a simple factorial generating program using the modified version of if:

(define (factorial n)
  (modified-if (= n 0)
               (* n (factorial (- n 1)))))

现在,当我调用上面的函数时,它将进入无限循环.为什么会发生这种情况?

Now, when I call the above function, it goes into an infinite loop. Why does that happen?

推荐答案

方案渴望评估.这意味着,除非您使用委派给这种特殊格式的特殊格式(例如if)或宏(例如condcase),否则将评估 all 子表达式首先.

Scheme has eager evaluation. This means that, unless you're using a special form (like if) or a macro (like cond or case) that delegates to such a special form, all subexpressions are evaluated first.

这意味着您的表情

(modified-if (= n 0)
             1
             (* n (factorial (- n 1))))

在运行modified-if之前,首先评估(* n (factorial (- n 1))). (它可以在(= n 0)之前或之后运行,但无论哪种方式,无论如何都将进行递归调用.)由于这是一个递归调用,这意味着您的程序将无限递归,并且最终堆栈用完了.

the (* n (factorial (- n 1))) is evaluated first, before modified-if is run. (It may be run before or after (= n 0), but it doesn't matter either way, the recursive call still happens regardless.) And since this is a recursive call, that means that your program will infinitely recurse, and you will eventually run out of stack.

这是一个简单的示例:考虑一下:

Here's a simple example: consider this:

(if #t
    (display "Yay!")
    (error "Oh noes!"))

因为if是一种特殊形式,并且它仅求值必要的分支,在这种情况下,它将仅求值(display "Yay!")而不求值(error "Oh noes!").但是,如果您转而使用modified-if,则两个表达式都将被求值,并且程序将引发错误.

Because if is a special form, and it only evaluates the necessary branch, in this case it will only evaluate (display "Yay!") and not evaluate (error "Oh noes!"). But if you switch to using your modified-if, both expressions will be evaluated, and your program will raise an error.

这篇关于Scheme中基本if表达式的修改.为什么会陷入无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆