-1

If I use the following code from chapter 1 of SICP it gives the correct answer.

(cond ((= a 4) 6) ((= b 4) (+ 6 7 a)) (else 25)) 

prints 16

If I replace the cond by an if it doesn't work

(if ((= a 4)6) ((= b 4) (+ 6 7 a)) (else 25))

gives error:

The object #f is not applicable.

What am I doing wrong? Why doesn't the if work?

N.B. This is from exercise 1.1 with the definitions:

(define a 3)
(define b (+ a 1))
darthcoder
  • 109
  • 3

1 Answers1

2

cond and if are two very different syntactic constructs. You can't simply substitute the name of one for the other.

If syntax:

(if test
    (then part)
    (else part))

Cond syntax:

(cond (test1 form11 ... form1n)
      (test2 form12 ... form2n)
      ...
      (else form1m ... formmn))

So the equivalent of:

(cond ((= a 4) 6) 
      ((= b 4) (+ 6 7 a))
      (else 25)) 

is:

(if (= a 4)
    6
    (if (= b 4)
        (+ 6 7 a)
        25))
Renzo
  • 26,848
  • 5
  • 49
  • 61
  • thanks a lot. i have one further query: what would be the correct form of the following : ```(if ((= b a) 6) 25)``` i have figured out how to use ```cond```, but i don't seem to understand ```if```. i mean to check for if b = a then 6 else 25. – darthcoder May 14 '17 at 12:35
  • As I said, the correct form is `(if condition then-part else-part)` so your example should be written `(if (= b a) 6 25)`. Keep in mind that in Scheme parentheses are significant, differently from almost all other languages. For isntance if you write `(if ((= b a) 6) 25)` this is interpreted as: `(if x 25)` (wrong because you have 2 arguments to `if` instead of 3), where x is `((= b a) 6)`, which is interpreted as: evaluate `(= b a)`, then apply the function returned to 6 (because of `( (...) 6)`), which produces another error since `(= b a)` returns `#t` or `#f` and not a function. – Renzo May 14 '17 at 13:17
  • Note that if you want to learn Scheme without letting lost with all those parentheses, you should align properly the code, and this can be greatly simplified by the use of a text editor that understand Schema syntax, like Emacs or DrRacket. – Renzo May 14 '17 at 13:23
  • thanks a lot. i just wrote in my notes that scheme parenthesis work differently from other languages (i got the correct form for if after a lot of trial and error). and you just explained it very succinctly and i understood it hopefully. thanks a lot again. – darthcoder May 14 '17 at 13:36