Page 1 of 1

Recursion Error

Posted: Thu Nov 16, 2006 5:50 pm
by 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

Code: Select all

(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

Code: Select all

(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?

Posted: Thu Nov 16, 2006 6:08 pm
by Grundle
Ahh, way to go n00ber. I just figured out why this is happening. Note the difference in the following statements

Code: Select all

(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 ;)

Posted: Thu Nov 16, 2006 6:37 pm
by Lutz
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