[ACCEPTED]-What happens in a Scheme 'cond' clause when the 'else' is omitted?-racket

Accepted answer
Score: 19

"else" is just a synonym for "true". The 21 way to read cond is as a series of tests, where 20 the first test that's true causes that form 19 to be evaluated.

(cond  ( (test) (do this) )
       ( (test) (do this) ) )

Here's your first one

 (cond ((eq? x 0) (display "zero\n"))
        (display "whatever\n")))

cond 18 looks at (eq? x 0) and determined that's false. The 17 next clause is (display "whatever\n"). It looks at display, and since 16 display is not nil, it's true. It then evaluates 15 the string "whatever\n", which simply evaluates to itself. So 14 the value of the cond is then "whatever\n".

Now, here's 13 you second one:

(cond ((eq? x 0 ) (display "zero\n"))
       (else (display "whatever\n"))))

Here, the first test is false, and 12 it goes on to the second one, which is else and 11 which evaluates to true. (If you think 10 about it, that's what the "else" means in 9 a normal if-then-else: "true for all the 8 cases where none of the previous tests were 7 true.")

Now, the form following it is (display "whatever\n"). That's 6 a function that sends the string argument 5 to the console and returns nothing because 4 that's what display happens to do. In another 3 scheme, it might return its string value 2 as well as printing it, in which case you'd 1 see

whatever
"whatever\n"
Score: 10

In the foo function, the cond statement evaluates 4 display as the condition to test. Since there is 3 indeed a symbol called display, it evaluates to 2 true, so the "whatever\n" is then evaluated as the result 1 of (foo 2).

More Related questions