There could be a macro to have for in with an iterator class.
Javascript uses next() and throw StopIteration
Java and haxe uses next() and hasNext()
A macro that transforms:
for i, ii in x()
statements
into:
var iter = x()
while (hasnext(iter)):
i, ii = next(iter)
statements
I'm not clever enough to understand macros, so I couldn't make one. btw, macros seem like the best feature, but aren't usable unless there are a large number of examples to learn from.
You can try something like this:
iterator each[T, U](it: var T): U =
mixin next, hasNext
while hasNext(it):
yield next(it)
type SomeIter = object
pos: int
data: seq[int]
proc hasNext(it: SomeIter): bool =
it.pos < it.data.len
proc next(it: var SomeIter): int =
result = it.data[it.pos]
inc it.pos
var x = SomeIter(pos: 0, data: @[4,5,6])
for t in each(x):
echo t
Why name it 'each' and not 'items', Jehan?
iterator items[T, U](it: var T): U =
mixin next, hasNext
while hasNext(it):
yield next(it)
#.. snip .. #
var x = SomeIter(pos: 0, data: @[4,5,6])
for t in x:
echo t
Orion: Why name it 'each' and not 'items', Jehan?
Because it was something I threw together quickly without much thought?