nastyfish
nastyfish

Reputation: 1

SICP lisp 'if' conditional expression explanation

I'm working through SICP and have gotten to the part about the square root code. I understood that 'if' statements could only be followed by single expressions. However, in the code,

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

I don't understand how the 3rd, 4th, and 5th lines are valid when the 'guess' and 'x' have already been stated as the consequent expressions for 'if'.

Upvotes: 0

Views: 532

Answers (3)

sarah
sarah

Reputation: 116

guess and x are arguments to the good-enough? predicate, "if" is selecting between the following guess and (sqrt-iter ...) expressions.

Upvotes: 3

liuyang1
liuyang1

Reputation: 1725

No, In scheme language, 'if' statements could followed by two or three expressions, not only one.

(if test-exp then-exp else-exp)

Even in some implement of scheme interpreter,'if' statements MUST followed by three expressions, 'else-exp' can not be ommitted.

More details read: http://classes.soe.ucsc.edu/cmps112/Spring03/languages/scheme/SchemeTutorialA.html#condexp

Upvotes: 1

Óscar López
Óscar López

Reputation: 235994

In some Scheme interpreters an if special form can be followed by one or two expressions after the condition, in others (for example: Racket) the condition must be followed by exactly two expressions. But in your code there are two expressions after the condition! it's more of an indentation problem, see:

(define (sqrt-iter guess x)
  (if (good-enough? guess x)       ; condition
      guess                        ; first expression  (consequent)
      (sqrt-iter (improve guess x) ; second expression (alternative)
                 x)))

To clarify: guess and x are not the consequent and alternative of the condition, they are the arguments for the good-enough? procedure in the expression (good-enough? guess x), which is just the condition part. Remember that the general structure of an if expression looks like this:

(if <condition>
    <consequent>
    <alternative>)

Where each part is an expression. For further details please refer to the documentation.

Upvotes: 6

Related Questions