'Understanding conditional scheme formatting? SICP exercise 1.6
I understand the big picture applicative vs normal order lesson here I think, but I'm struggling with:
(define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause)))
Eva demonstrates the program for Alyssa:
(new-if (= 2 3) 0 5) 5
(new-if (= 1 1) 0 5) 0
And for that matter:
(cond (= 2 3) 0 5) 3
(cond (= 1 1) 0 5) 1
Could you walk me through like a child why these return these values? They are all just predicates with no consequent expressions, right?
Solution 1:[1]
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
(new-if (= 2 3) 0 5)
5
(new-if (= 1 1) 0 5)
0
when you call first new-if procedure as you can see you test predicate (= 2 3) if it is true it returns then-clause which is 0 and if it is not true then it returns else-clause which is 5. For second new-if procedure predicate is (= 1 1) which is true so it returns then-clause which is 0.
Actually I don't know why these cond expressions returns these values but you should normally use cond like this after cond every parenthesis includes a clause
(cond (<p1><e1>)
(<p2><e2>)
...
(<pn><en>))
for your example
(cond ((= 2 3) 0)
(5))
if there is no expression after test in the clause it returns test value as the result which is 5 here or you can call with else either
(cond ((= 2 3) 0)
(else 5))
Solution 2:[2]
Use the substitution method, as explained in the previous chapter.
(new-if (= 2 3) 0 5)
—> (new-if #f 0 5)
—> (cond (#f 0)
(else 5))
—> 5
and
(new-if (= 1 1) 0 5)
—> (new-if #t 0 5)
—> (cond (#t 0)
(else 5))
—> 0
Your cond examples have bad syntax, but if you have a clause like
(cond
(= 2 3)
...
it is equivalent to
(cond
(= (begin 2 3))
...
that is, the condition is =, and 2 3 is a sequence of expressions that constitute the body.
The value of such a sequence of expressions is the value of the last expression.
(The book will not use such sequences until side effects are introduced, around half way through the book.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | molbdnilo |
