7.22 WHILE-DO constructs. 4tH 4tH Forth compiler
विज्ञापन
विज्ञापन
CHAPTER 7. 4TH FUNDAMENTALS
11 1 do i . cr 2 +loop
75
This one will produce exactly what you asked for. An increment by two. This one will produce all negative numbers from -1 to -10:
-11 -1 do i . cr -1 +loop
Note that the step is not a literal expression. You can change the step if you want to, e.g.:
32767 1 do i . i +loop
This will print: 1, 2, 4, 8, all up to 16384. Pretty flexible, I guess. You can break out of a loop by using ’LEAVE’. Note that ’LEAVE’ only sets the index to the value of the limit: it doesn’t branch or anything. Make sure that there is no code left between ’LEAVE’ and
’LOOP’ that you don’t want to execute. So this is okay:
10 0 do i dup 5 = if drop leave else . cr then loop
And this is not:
10 0 do i dup 5 = if drop leave then . cr loop
Since it will still get past the ’.’ before leaving. In this case you will catch the error quickly, because the stack is empty.
7.22
WHILE-DO constructs
A WHILE-DO construction is a construction that will perform zero or more iterations. First a condition is checked, then the body is executed. Then it will branch back to the condition.
In 4tH it looks like this:
BEGIN <condition> WHILE <body> REPEAT
The condition will have to evaluate to TRUE in order to execute the body. If it evaluates to
FALSE it branches to just after the REPEAT. This example does a Fibbonaci test.
: fib 0 1 begin dup >r rot dup r> > while
\ condition rot rot dup rot + dup . \ body repeat drop drop drop ; \ after loop executed
You might not understand all of the commands, but we’ll get to that. If you enter "20 fib" you will get:
1 2 3 5 8 13 21
This construct is particularly handy if you are not sure that all data will pass the condition.
डाउनलोड
विज्ञापन