[racket] what's wrong with my code?

From: Stephen Bloch (bloch at adelphi.edu)
Date: Sun Jan 20 21:24:15 EST 2013

On Jan 20, 2013, at 8:50 PM, Robert Hume <rhume55 at gmail.com> wrote:

> I'm really stuck trying to figure this out.  Any pointers are useful!  Here's the problem:
> 
> f(n) = n if n<4 
> and 
> f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) + 4f(n - 4) if n>= 4
> 
> Here's my solution so far -- any one know what I'm doing wrong?
> 
> (define (f n)
> 
>   (define (f-iter result i)
>     (if (> i 4)
>         result
>         (f-iter (+ result (* i (- n i))) (+ i 1))
>     )
>   )
> 
>   (if (< n 4)
>       n
>       (f-iter 0 1)
>   )
> 
> )
> 
> (f 4) ;; should produce 10, produces 10
> (f 5) ;; should produce 26, produces 20
> (f 6) ;; should produce 63, produces 30

You don't have any test cases for the base case (n < 4).

Your definition has a base case of n <= 4, rather than n < 4 as stated in the assignment.

I would write a simple version of the function (without the nested function definition, just defined directly from the assignment) first and make sure it works, then do the iterative version as an optimization.

I would write "f-iter" as a stand-alone function, writing test cases for it as usual, and only after it worked, consider moving it inside "f".  Unless it depended on something in the containing function, which it doesn't… no, wait, it refers to n, the parameter of the outer function.  Why?  And why doesn't the definition refer to previous values of the function?


Stephen Bloch
sbloch at adelphi.edu



Posted on the users mailing list.