Loops/Wrong ranges: Difference between revisions

Added Forth impl
(Added Wren)
(Added Forth impl)
Line 394:
2 2 0 <range> => Exception: divide by zero.
0 0 0 <range> => Exception: divide by zero.
</pre>
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
Forth, being a language that assumes a smart programmer, has absolutely no qualms with integer overflow or zero increments; it simply does what you told it to, not what you meant. This is, of course, dangerous code, so another looping construct is provided that ''does'' check whether the bounds and increment are valid.
===DO===
<lang forth>: test-seq ( start stop inc -- )
cr rot dup ." start: " 2 .r
rot dup ." stop: " 2 .r
rot dup ." inc: " 2 .r ." | "
-rot swap do i . dup +loop drop ;
-2 2 1 test-seq
-2 2 0 test-seq
-2 2 -1 test-seq
-2 2 10 test-seq
2 -2 1 test-seq
2 2 1 test-seq
2 2 -1 test-seq
2 2 0 test-seq
0 0 0 test-seq</lang>
{{out}}
Some of these loop infinitely, and some under/overflow, so for the sake of brevity long outputs will be truncated by <code>...</code>.
<pre>
start: -2 stop: 2 inc: 1 | -2 -1 0 1
start: -2 stop: 2 inc: 0 | -2 -2 -2 -2 -2 ...
start: -2 stop: 2 inc: -1 | -2 -3 -4 -5 ... 5 4 3 2
start: -2 stop: 2 inc: 10 | -2
start: 2 stop: -2 inc: 1 | 2 3 4 5 ... -6 -5 -4 -3
start: 2 stop: 2 inc: 1 | 2 3 4 5 ... -2 -1 0 1
start: 2 stop: 2 inc: -1 | 2
start: 2 stop: 2 inc: 0 | 2 2 2 2 2 ...
start: 0 stop: 0 inc: 0 | 0 0 0 0 0 ...
</pre>
===?DO===
This is almost exactly the same as the above DO, but the bounds are checked for validity first.
<lang forth>: test-seq ( start stop inc -- )
cr rot dup ." start: " 2 .r
rot dup ." stop: " 2 .r
rot dup ." inc: " 2 .r ." | "
-rot swap ?do i . dup +loop drop ;
-2 2 1 test-seq
-2 2 0 test-seq
-2 2 -1 test-seq
-2 2 10 test-seq
2 -2 1 test-seq
2 2 1 test-seq
2 2 -1 test-seq
2 2 0 test-seq
0 0 0 test-seq</lang>
{{out}}
Some of these loop infinitely, and some under/overflow, so for the sake of brevity long outputs will be truncated by <code>...</code>. If there is no output beyond the <code>|</code> symbol, then the loop was not entered.
<pre>
start: -2 stop: 2 inc: 1 | -2 -1 0 1
start: -2 stop: 2 inc: 0 | -2 -2 -2 -2 -2 ...
start: -2 stop: 2 inc: -1 | -2 -3 -4 -5 ... 5 4 3 2
start: -2 stop: 2 inc: 10 | -2
start: 2 stop: -2 inc: 1 | 2 3 4 5 ... -6 -5 -4 -3
start: 2 stop: 2 inc: 1 |
start: 2 stop: 2 inc: -1 |
start: 2 stop: 2 inc: 0 |
start: 0 stop: 0 inc: 0 |
</pre>
 
Anonymous user