Recursion Error

Q&A's, tips, howto's
Locked
Grundle
Posts: 15
Joined: Mon Mar 28, 2005 9:26 pm

Recursion Error

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

Grundle
Posts: 15
Joined: Mon Mar 28, 2005 9:26 pm

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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

Locked