Tuesday, 3 October 2017

To DO or not to DO - what NEXT?

Every Forther knows that if you want an indexed loop you use the DO LOOP or DO +LOOP words. In Tachyon I also had the ADO word which basically worked like a combined BOUNDS DO. Now there is no more DO, and with no more ADO then, what do we do?

The other way to loop without an index was simply to use FOR NEXT for a simple counted loop but that doesn't allow for an index or a variable step. Well, it doesn't normally. In order to squeeze more into the kernel I turned to enhancing FOR NEXT so that while it still works like the standard FOR NEXT, it also has indexing and variable step capabilities. If nothing else is specified the FOR NEXT loop maintains an index starting at zero and stepping by +1. Here is how it works:
..  10 FOR I . SPACE NEXT 0 1 2 3 4 5 6 7 8 9  ok
Now what if we want to start from 100 instead of zero? Use 100 FROM and also if we want to step by 5 use 5 BY prior to the FOR like this:
..  CR 100 FROM 5 BY 10 FOR I . SPACE NEXT
100 105 110 115 120 125 130 135 140 145  ok


Another example is displaying the alphabet (just to keep it tight):
..  'A' FROM 26 FOR I EMIT NEXT ABCDEFGHIJKLMNOPQRSTUVWXYZ ok 
and back to front
..  'Z' FROM -1 BY 26 FOR I EMIT NEXT ZYXWVUTSRQPONMLKJIHGFEDCBA ok

BTW, the FOR NEXT method also stacks a branch address so it is fast. Using LAP <code> LAP .LAP to measure:
..  1,000,000 CR LAP FOR NEXT LAP .LAP
48000240 cycles at 80MHz = 600.003ms  ok
 
Divide that down by a million and that is 600ns overhead each loop (plus 3us setup).

No comments:

Post a comment