Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a while() loop in Gforth

Tags:

forth

gforth

I'd like to write a while() loop in Gforth. Unfortunately, the only tutorial online isn't useful due to a lack of examples, and examples on counted loops (what I'm not looking for) appear fundamentally different.

What are some concrete examples of how to represent something like this?

while (x > 3) { print(x); x--; }

Or really, just some concrete way to represent anything of the form:

while (predicate) { expression(s) }
like image 951
Phillip Carter Avatar asked Mar 04 '15 22:03

Phillip Carter


1 Answers

Your first piece of code translates to:

\ Assuming x is on the top of the stack.
begin dup 3 > while dup . 1- repeat

\ Or if x is in memory.
begin x @ 3 > while x ? -1 x +! repeat

And the second:

begin predicate while expressions repeat
like image 110
Lars Brinkhoff Avatar answered Nov 03 '22 02:11

Lars Brinkhoff