Sysop: | Amessyroom |
---|---|
Location: | Fayetteville, NC |
Users: | 23 |
Nodes: | 6 (0 / 6) |
Uptime: | 54:07:32 |
Calls: | 583 |
Files: | 1,139 |
D/L today: |
179 files (27,921K bytes) |
Messages: | 111,699 |
On Sat, 28 Jun 2025 21:01:48 +0000, Anton Ertl wrote:
sean@conman.org writes:
-aWhat is the difference between FOR/NEXT and DO/LOOP?-a Don't they do the >>> same thing?
FOR ... NEXT on one system does not do the same thing as FOR ... NEXT
on some other systems, and they all behave different from DO ... LOOP.
Correct. Here are variants with iterators that even run on gforth 0.7.9:
\ ====== <n> FOR# .. #TIMES ==================================================
\ original: machine code
\ demo variant: slow Forth
: _ITERATE \ end xt
-a-a-a-aswap
-a-a-a-aBEGIN dup 0>
-a-a-a-aWHILE over execute 1-
-a-a-a-aREPEAT 2drop ;
: FOR# postpone [: ; IMMEDIATE
: #TIMES postpone ;] postpone _iterate ; IMMEDIATE
\ ====== <n> FOR .. N M .. NEXT ==============================================
On 03/07/2025 20:33, minforth wrote:
On Sat, 28 Jun 2025 21:01:48 +0000, Anton Ertl wrote:
sean@conman.org writes:
-aWhat is the difference between FOR/NEXT and DO/LOOP?-a Don't they do >>>> the
same thing?
FOR ... NEXT on one system does not do the same thing as FOR ... NEXT
on some other systems, and they all behave different from DO ... LOOP.
Correct. Here are variants with iterators that even run on gforth 0.7.9:
\ ====== <n> FOR# .. #TIMES
==================================================
\ original: machine code
\ demo variant: slow Forth
: _ITERATE \ end xt
-a-a-a-a-aswap
-a-a-a-a-aBEGIN dup 0>
-a-a-a-a-aWHILE over execute 1-
-a-a-a-a-aREPEAT 2drop ;
: FOR# postpone [: ; IMMEDIATE
: #TIMES postpone ;] postpone _iterate ; IMMEDIATE
\ ====== <n> FOR .. N M .. NEXT
==============================================
I've found looping quotations useful but I like to include the quotation inside the loop e.g. (without the syntactic sugar and moving the
iterator inside the quotation):
: downcount begin [: dup 0> if dup . 1- then ;] over 0> while execute
repeat 2drop ;
10 downcount \ displays 10 9 8 7 6 5 4 3 2 1-a ok
Advantages are:
1) The xt is not passed to the quotation and so doesn't get in the way.
2) The xt is loaded as a literal when the quotation exits.
3) The quotation can exit the loop early by EXITing with 0 on the stack.