gforth
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


From: Terrence Brannon
Subject: [gforth] attempt to use WHILE leads to empty stack (loop issues)
Date: Sat, 6 Mar 2010 14:32:29 -0500

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. 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.

I hand-traced it, and it seems fine from hand-tracing.



: halve-n ( n -- n/2 ) 2/ ;

: init-counter-for-number-of-halves-needed ( -- 0 ) 0 ;

: insure-n-is-greater-than-or-equal-to-0 ( n counter -- n counter flag )
  over 0> ;

: halve-n-and-increment-counter { n counter -- n/2 counter+1 }
  n 2/ counter 1+ ;

: log2 ( +n1 -- n2 )
  assert( dup 0> )      
  halve-n
  init-counter-for-number-of-halves-needed
  BEGIN
    insure-n-is-greater-than-or-equal-to-0
    WHILE \ n >= 0
      halve-n-and-increment-counter { n counter -- n/2 counter+1 }
  REPEAT
  NIP \ n, leaving the counter
  ;



sh-3.2$ ./gforth
Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'
Type `bye' to exit
include log2.fs
include log2.fs  ok
8
8  ok
\ dup does not behave at command-line as in a program... so omitting
\ dup does not behave at command-line as in a program... so omitting   ok
halve-n
halve-n  ok
init-counter-for-number-of-halves-needed .s
init-counter-for-number-of-halves-needed .s <2> 4 0  ok
insure-n-is-greater-than-or-equal-to-0
insure-n-is-greater-than-or-equal-to-0  ok
.s
.s <3> 4 0 -1  ok
drop \ simulate WHILE consuming the true flag
drop \ simulate WHILE consuming the true flag  ok
.s
.s <2> 4 0  ok
halve-n-and-increment-counter .s
halve-n-and-increment-counter .s <2> 2 1  ok
halve-n-and-increment-counter .s
halve-n-and-increment-counter .s <2> 1 2  ok
halve-n-and-increment-counter .s
halve-n-and-increment-counter .s <2> 0 3  ok
nip .s
nip .s <1> 3  ok




reply via email to

[Prev in Thread] Current Thread [Next in Thread]