Recursion Error

Started by Grundle, November 16, 2006, 09:50:49 AM

Previous topic - Next topic

Grundle

I am working with the latest newlisp-TK on a windows platform.  I have written the following simple recursive algorithm for the fibonacci sequence



(define (fib 'val)
  (if (< val 2)
   1
   (+ (fib (- val 1)) (fib (- val 2)))))


What is strange is that when I try to do either of the following statements



(fib 3)

(set 'n 3)
(fib n)


It will always return 1.  I have run the algorithm through the debugger supplied, and I have been able to determine that it is saying that all values are less than 2, which results in an automatic return of 1.  Why would it be doing this?

Grundle

#1
Ahh, way to go n00ber.  I just figured out why this is happening.  Note the difference in the following statements



(define (fib val) .... )

(define (fib 'val) ... )


The first define is of course correct.  The second will cause this behavior, because I believe that it is setting a variable at that point in stead of allowing a variable to be passed in.  



Such a silly mistake :D  Please laugh accordingly ;)

Lutz

#2
This is what is happening:



'val' is passed as a symbol and therefor cannot binf to the number passed. The contents of 'val' beeing 'nil' in (< val 2) results in the comparison (< nil 2), which is 'true'. The compare operators when given operands of different types compare type values as of the following order:



Atoms: nil, true, integer or float, string, symbol, primitive

Lists: quoted list/expression, list/expression, lambda, lambda-macro



Lutz



ps:  http://newlisp.org/newlisp_manual.html#logical">http://newlisp.org/newlisp_manual.html#logical