Page 1 of 1

Numeric for loop

PostPosted: Tue Mar 25, 2008 12:44 am
by Charles
In development, I added the new "for" loop syntax for the numeric for loop. The old syntax will still be supported for one year, but its use of .. ++ and -- didn't match anything else in the language. The new syntax uses the same "for x in" as an "enumerable for loop" and the rest of the statement matches slicing (list[start:stop:step]):
# forms:
for x in start : stop : step
print x
for x in start : stop # step of 1 is assumed
print x
for x in stop # start of 0 is assumed
print x

# examples:
list = ['qwerty', 'dvorak']
for i in list.count
list[ i] = list[ i].toUpper
for i in 0 : 100 : 2
print i

The integers generated match the indexes of a list (or array), whether the entire thing or a slice.

Unlike the old numeric for loop, the parameters to the loop are evaluated only once. In other words, the "stop" and the "step" are not re-evaluated each iteration of the loop. I think this is more clear and can also be more efficient. It's also more like using a range() function or enumerator.

If you need to re-evaluate the boundary and/or step each time, use the general purpose "while" loop.

Re: Numeric for loop

PostPosted: Tue Mar 25, 2008 6:34 am
by Mirco
I think here is a little bug:
for x in 10 : 2  # Should do nothing, but prints 10, 11, 12
print x
if x == 12
break

for x in 10 : 0 : 2 # Should do nothing, but prints 10, 12
print x
if x == 12
break

Re: Numeric for loop

PostPosted: Tue Mar 25, 2008 9:14 am
by Charles
Thanks for the report. Fixed.

The code for determining the direction was based on comparing the stop and start instead of looking at the step. It's as if I were thinking in the back of my head that "for x in 10 : 2" should give [10, 9, ..., 4, 3] if the step were left out. That doesn't seem unreasonable, but it could be surprising for "for x in i : j" which could then go backwards or forwards depending on the values of i and j.