-1

I am new to Scheme, and I am learning SICP now. I write some code for Exercise 2.20, to return a list whose element shares the same parity with the first one:

(define (same-parity first . rest)
    (define (same-parity-iter ret rest)
        (if (null? rest)
            ret
            ((if (odd? (+ first (car rest)))
                 (same-parity-iter ret (cdr rest))
             (same-parity-iter (append ret (list (car rest))) (cdr rest))))))
    (same-parity-iter (list first) (cdr rest)))

and run it with some example:

(same-parity 1 2 3 4 5)

then there is the error:

The object (1 3 5) is not applicable.

Do you know how to fix this error? I guess it treats the return value (1 3 5) as a function, but have no idea how to fix it. Thank you.

cao lei
  • 891
  • 1
  • 9
  • 19
  • You have too many open parentheses on line 5. That means the return value of the recursive call gets treated as a function. – Fred Foo Jun 16 '14 at 12:49
  • 1
    Probable duplicate of [The object ___ is not applicable](http://stackoverflow.com/q/22976298/1281433). `(x y)` is a function call. When you have `((if ...) ...)` you're trying to call whatever `(if ...)` returns as a function. `(if ...)` returns `(1 3 5)`, and you're trying to call it as a function. – Joshua Taylor Jun 16 '14 at 13:15
  • By the way, searching on Google for `"the object" "is not applicable" site:stackoverflow.com` turned up that duplicate as well as a bunch of others that probably could have solved your problem. It's generally a good debugging tip to through the specific error message (but usually without the specific data (in this case `(1 3 5)`)) into a search engine first. – Joshua Taylor Jun 16 '14 at 13:22

1 Answers1

0

There is a ( too much in your code. Have a look at the second if:

((if (odd? (+ first (car rest)))
     (same-parity-iter ret (cdr rest))
     (same-parity-iter (append ret (list (car rest))) (cdr rest)))))

Basically, you are telling the interpreter (or compiler): take the result of the

(if (odd? (+ first (car rest)))
     (same-parity-iter ...)
     (same-parity-iter ...))

and apply it as a function. The result is a list of integers, which is not a function -- hence the error. Change the code to

(define (same-parity first . rest)
  (define (same-parity-iter ret rest)
    (if (null? rest)
        ret
        (if (odd? (+ first (car rest)))
            (same-parity-iter ret (cdr rest))
            (same-parity-iter (append ret (list (car rest))) (cdr rest)))))
    (same-parity-iter (list first) (cdr rest)))
Dirk
  • 30,623
  • 8
  • 82
  • 102