Reputation: 1299
I am going through the book Structure and Interpretation of Computer Programming, which uses Scheme, and I just got through a portion on recursion. I wrote a program for 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. Write a procedure that computes f by means of an iterative process.
I wrote the code at repl.it and when I run the procdure with the input 2
, it gives me the error: Error: 2 is not a function [fRecurse, (anon)]
. Can somebody explain to me what this means and how I can fix it? Why is it expecting my input to be a function?
Code:
(define (fRecurse n)(
(cond ((< n 3) n)
((>= n 3)
(+ (procRecurse (- n 1))
(* 2 (f (- fRecurse 2)))
(* 3 (f (- fRecurse 3))))))))
(fRecurse 2)
Upvotes: 2
Views: 59
Reputation: 5456
The error is due to an extra pair of parentheses before (cond...)
. To fix the issue, we simply remove the extra pair of parentheses:
(define (fRecurse n)
(cond ((< n 3) n)
((>= n 3)
(+ (fRecurse (- n 1))
(* 2 (fRecurse (- n 2)))
(* 3 (fRecurse (- n 3)))))))
(fRecurse 2)
And some additonal fixes I made to your example to make it work correctly:
f
to fRecurse
procRecurse
to fRecurse
(* 2 (f (- fRecurse 2)))
to (* 2 (fRecurse (- n 2)))
(* 3 (f (- fRecurse 3)))
to (* 3 (fRecurse (- n 3)))
See the updated repl.it
Upvotes: 2