21.3.8 BEGIN..WHILE..REPEAT. 4tH 4tH Forth compiler
Reklama
Reklama
CHAPTER 21. PORTING GUIDE 387
21.3.8
BEGIN..WHILE..REPEAT
4tH allows you to use multiple WHILE’s in a BEGIN..WHILE..REPEAT construct. ANS-
Forth allows that too, but requires an extra ’THEN’ for each additional ’WHILE’. In short, this is the 4tH version:
0 begin dup 10 < while 1+ dup 5 mod while 1+ repeat
And this is the ANS-Forth version:
0 begin dup 10 < while 1+ dup 5 mod while 1+ repeat then
To make this work, we have to resort to conditional compilation:
0 begin dup 10 < while 1+ dup 5 mod while 1+ repeat
[undefined] 4th# [if] then [then]
It’s not beautiful, but it works. The same applies when ’UNTIL’ is used instead of ’RE-
PEAT’. BEGIN..WHILE..AGAIN constructs are not supported by ANS-Forth, so be careful when considering ’AGAIN’ too much of an alias of ’REPEAT’. Also bear in mind that
DONE..DONE clauses can be defined in ANS-Forth, but still require conditional compilation if you resort to multiple ’WHILE’s.
21.3.9
CASE..OF..ENDOF..ENDCASE
Many users wonder why this ”essential” construct is missing in 4tH. The explanation is pretty simple: it is horrible! First, this construct puts a heavy burden on the controlstack, which is pretty shallow in 4tH. Why? Because it is essentially a nested IF..ELSE..THEN
construct as you will see later on. Second, these kinds of problems are better handled by a lookup table. 4tH has excellent support for lookup tables, much better than other Forths.
Of course, sometimes you just want to convert a program and don’t feel like redesigning it. Fortunately, converting CASE..OF..ENDOF..ENDCASE constructs is pretty straightforward. It only requires four simple steps. Let’s examine this simple example:
: .WEEKDAY ( daynum --- )
CASE
1 OF ." Sunday" ENDOF
2 OF ." Monday" ENDOF
3 OF ." Tuesday" ENDOF
4 OF ." Wednesday" ENDOF
5 OF ." Thursday" ENDOF
6 OF ." Friday" ENDOF
7 OF ." Saturday" ENDOF
ENDCASE ;
Step 1: Replace ENDOF with ELSE and eliminate CASE
: .WEEKDAY ( daynum --- )
1 OF ." Sunday" ELSE
2 OF ." Monday" ELSE
3 OF ." Tuesday" ELSE
4 OF ." Wednesday" ELSE
5 OF ." Thursday" ELSE
6 OF ." Friday" ELSE
7 OF ." Saturday" ELSE
ENDCASE ;
Stáhnout
Reklama