|
From: | Elko Tchernev |
Subject: | Re: [gforth] naive fibonacci |
Date: | Sat, 06 Mar 2010 21:59:08 -0500 |
User-agent: | Thunderbird 2.0.0.23 (Windows/20090812) |
Terrence Brannon wrote:
I [found](http://bit.ly/ar7uDi) a couple of naive fibonacci programs by Bill Spight that work: : FIB ?DUP CASE 0 of 1 endof 1 of 1- RECURSE 1 endof 1- RECURSE TUCK + ENDCASE ; : FIB DUP 0= IF 1 ELSE 1- RECURSE TUCK + THEN ; But I would like to know why mine does not work: : fib { n -- fibn } assert( n 0>= ) n CASE 0 OF 0 ENDOF 1 OF 1 ENDOF 2 OF 1 ENDOF ( otherwise ) n 1 - recurse n 2 - recurse + ENDCASE ;
There is a non-explicit DROP before the ENDCASE. That's because the case parameter has to disappear at some point. Change your code in this way:
> ( otherwise ) n 1 - recurse n 2 - recurse + SWAPThis way, the parameter will be dropped, not your computed Fib value, and it will work.
In general, CASE is not a very useful or used construct in Forth; this is not C. The less you use it, the better.
[Prev in Thread] | Current Thread | [Next in Thread] |