gforth
[Top][All Lists]

## Re: [gforth] attempt to use WHILE leads to empty stack (loop issues)

 From: Anton Ertl Subject: Re: [gforth] attempt to use WHILE leads to empty stack (loop issues) Date: Sun, 7 Mar 2010 15:43:23 +0100 User-agent: Mutt/1.5.18 (2008-05-17)

```On Sat, Mar 06, 2010 at 02:32:29PM -0500, Terrence Brannon wrote:
> re:
> http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/General-Loops-Tutorial.html
>
> First, the enormous amount of stack dancing really made this program
> hard to follow.

You mean, in this example:

: log2 ( +n1 -- n2 )
\ logarithmus dualis of n1>0, rounded down to the next integer
assert( dup 0> )
2/ 0 begin
over 0> while
1+ swap 2/ swap
repeat
nip ;

You ain't seen nothing yet.  Or, in other words, this is not an
example that would be considered as having a lot of stack dancing by
most Forth programmers.

The pattern

( x1 x2 ) update-x1 swap update-x2 swap ( x1' x2' )

is typical when two values have to be updated.

> As a person deciding what language to study, I
> immediately began to think "I think this stack dancing is very very
> confusing. Maybe I should look at another language." So, I tried to
> rewrite it, but for some reason, the stack is empty when it
> terminates.

Your rewrite appears to be an example of overfactoring.  If you want
to get rid of stack manipulation, you can do it with locals within one
colon definition, e.g.:

: log2 { n1 -- n2 }
\ logarithmus dualis of n1>0, rounded down to the next integer
assert( n1 0> )
n1 2/ 0 begin { n count }
n 0> while
n 2/ count 1+
repeat
count ;

This is pretty Gforth-specific, though (locals withing control
structures are not universally supported).  If you wonder why COUNT is