Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

SICP exercise 1.11

Name: Anonymous 2009-03-05 10:24

Exercise 1.11. A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n -
3) if n> 3. Write a procedure that computes f by means of a recursive process.


(define (f n)
    (cond ((< n 3) n)
    (else ((+ (f (- n 1))
            (*
                (f (- n 2)) 2)
            (*
                (f (- n 3)) 3))))))


It gives me "The object 4 is not applicable".
Can you guys help me?

Name: Anonymous 2009-03-05 16:31

Since you're reading your SICP, I'll help him!

When you wrap something in parentheses it will be evaluated with the first symbol as a function and the following symbols as parameters.
So (+ 5 2) is the function + with arguments 5 and 2.
But what happens if you write ((+ 5 2))?  It thinks there is a nested function, so it evaluates the inner list (+ 5 2) first, and then it tries to evaluate the result inserted into the place where (+ 5 2) was, i.e. (7).  Since there's no function called 7 it complains.

If that confuses you, you may want to review the substitution model detailed in section 1.1.5.  The video lecture on the same subject may also be helpful, it's 1b and can be viewed or downloaded here <http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/>;

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List