aga
aga

Reputation: 29416

Unexpected behavior of cond statement

I need to write the function which works this way: if its argument is less than 3, it has to return the argument, otherwise it returns f(n-1) + f(n-2) + f(n-3). The function has to generate iterative (not recursive) process.
Now, I have this variant of my function:

(define (fi n)
    (define (fiHelper x1 x2 x3 c)
        (cond ((= c 2) x3)
            (else (fiHelper x2 x3 (+ x1 x2 x3) (- c 1)))))
    (cond ((< n 3) n)
        (else fiHelper 0 1 2 n)))

It always returns me the n which I've passed into it, no matter what I pass, for example it returns 10 if I've passed 10, it returns 17 if I've passed 17 and so on. I've rewritten it with if statement like so:

(define (fi n)
    (define (fiHelper x1 x2 x3 c)
        (cond ((= c 2) x3)
            (else (fiHelper x2 x3 (+ x1 x2 x3) (- c 1)))))
    (if (< n 3) 
        n
        (fiHelper 0 1 2 n)))

And it works as expected - returns 230 for the n equals 10. I can't figure out what's the difference between cond and if which causes this behavior.

Upvotes: 0

Views: 50

Answers (2)

Georg Fuss
Georg Fuss

Reputation: 315

The error in your code was for I not so easy to find. I inserted a "(display "HelferFoo") in the foo fiHelper and noticed then that this foo was never called.

Georg Fuss

Upvotes: 0

Jose Torres
Jose Torres

Reputation: 347

You want (else (fiHelper 0 1 2 n)), not (else fiHelper 0 1 2 n). The first expression calls the helper function; the second one just evaluates the symbols fiHelper, 0, 1, 2, taking the value of the last one.

Upvotes: 2

Related Questions