Loops/Wrong ranges: Difference between revisions

Content added Content deleted
Line 1,246: Line 1,246:
0
0
</pre>
</pre>

=={{header|Nim}}==
In Nim, ranges are used in “for loops” with iterators “countup” and “countdown”. These iterators accept only positive steps which means that a negative step must be translated using iterator “countdown”. Using this convention, the given ranges can be expressed either using “countup” or using “countdown” according to the sign of the step. If the step is zero, an error is detected at compile time or at runtime.

The following program display the values yielded by “countup” our “countdown” for the given ranges:

<lang Nim>import sequtils, strformat

proc displayRange(first, last, step: int) =

stdout.write &"({first:>2}, {last:>2}, {step:>2}): "

echo if step > 0: ($toSeq(countup(first, last, step)))[1..^1]
elif step < 0: ($toSeq(countdown(first, last, -step)))[1..^1]
else: "not allowed."

for (f, l, s) in [(-2, 2, 1), (-2, 2, 0), (-2, 2, -1),
(-2, 2, 10), (2, -2, 1), (2, 2, 1),
(2, 2, -1), (2, 2, 0), (0, 0, 0)]:
displayRange(f, l, s)</lang>

{{out}}
<pre>(-2, 2, 1): [-2, -1, 0, 1, 2]
(-2, 2, 0): not allowed.
(-2, 2, -1): []
(-2, 2, 10): [-2]
( 2, -2, 1): []
( 2, 2, 1): [2]
( 2, 2, -1): [2]
( 2, 2, 0): not allowed.
( 0, 0, 0): not allowed.</pre>


=={{header|Perl}}==
=={{header|Perl}}==