HaxeFoundation / haxe.org-comments

Repository to collect comments of our haxe.org websites
2 stars 2 forks source link

[code.haxe.org] Data structures - Stepped iterator #14

Open utterances-bot opened 5 years ago

utterances-bot commented 5 years ago

Stepped iterator - Data structures - Haxe programming language cookbook

Haxe has a special range operator for(i in 0...5) to iterate forward. This does not allow to modify i in place, thus you cannot make it iterate in steps.

https://code.haxe.org/category/data-structures/step-iterator.html

nadako commented 5 years ago

A good addition to this would be to have a

public static inline function intIter(start, end, step) {
    return new StepIterator(start, end, step);
}

One could then do import StepIterator.intIter in their module (or imports.hx) and write less verbose:

for (i in intIter(0, 10, 2) { ... }
Gama11 commented 5 years ago

In theory, you could even have this awesome syntax with a static extension on IntIterator? :)

for (i in (0...10).step(2)) { ... }
nadako commented 5 years ago

Too much parens for my taste, but nice idea, lol! :)

Gama11 commented 5 years ago

Ah, so that's why you didn't add a ). :D

I think it's much more readable because in the other one you have to figure out which int parameter is what. But I guess you could have intIter(0...10, 2) for better readability too.

nadako commented 5 years ago

But I guess you could have intIter(0...10, 2) for better readability too.

Hah, this actually works (and inlines):

public static inline function stepped(i:IntIterator, step:Int) {
    return @:privateAccess new StepIterator(i.min, i.max, step);
}
RealyUniqueName commented 5 years ago

you could even have this awesome syntax with a static extension

You could have similar not-so-awesome syntax :)

using Iterators;
for(i in 0.to(10).step(2)) {}
for(i in 10.to(0)) {}
for(i in 10.to(0).step(-2)) {}

https://github.com/RealyUniqueName/Iterators/blob/master/src/Iterators.hx#L114