What's the explanation for Exercise 1.6 in SICP?

前端 未结 6 508
一个人的身影
一个人的身影 2021-01-30 16:08

I\'m just beginning to work through SICP (on my own; this isn\'t for a class), and I\'ve been struggling with Exercise 1.6 for a couple of days and I just can\'t seem to figure

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 16:30

    Previous answers are great. I'll add another one that explains in a more thorough way.

    Another way to think of this difference is like this: How is the recursion using if stopping at some point and the one using new-if looping forever?

    First lets see how these two ifs work in general and then how they work for this case.

    if

    This is explained by @alex-vasi:

    To evaluate an if expression, the interpreter starts by evaluating the part of the expression. If the evaluates to a true value, the interpreter then evaluates the and returns its value. Otherwise it evaluates the and returns its value.

    new-if

    This is explained by @Schmudde:

    All arguments are fully evaluated before the procedure is called.

    How is the recursion using if stopping at some point?

    It's stopping because at the point where the guess is good enough (ie (good-enough? guess x) is true), we will have:

    (if (good-enough? guess x)
        guess
        (sqrt-iter (improve guess x)
                   x)))
    

    And since the predicate is now true, the interpreter will evaluate the consequent (which is guess), return its value and will no longer evaluate the alternative (which is (sqrt-iter (improve guess x) x)).

    So if actually evaluates (sqrt-iter (improve guess x) x) recursively up until the guess is good enough. Then it stops the recursion.

    How is the recursion using new-if looping forever?

    As with if, with new-if (sqrt-iter (improve guess x) x) will be evaluated recursively up until the guess is good enough.

    But then it will keep evaluating (sqrt-iter (improve guess x) x) again and again. Why? Because when evaluating:

    (new-if (good-enough? guess x)
        guess
        (sqrt-iter (improve guess x)
                   x)))
    

    since new-if is a procedure, it will not check if (good-enough? guess x) is true or not in order to decide to evaluate either guess or (sqrt-iter (improve guess x)). What it will do is that it will evaluate (good-enough? guess x), guess and (sqrt-iter (improve guess x)) because those are the arguments of the procedure. So even when guess is good enough it will keep calling (sqrt-iter (improve guess x)) recursively :/.

提交回复
热议问题