The following code segfaults when run. The call 'finished(next)' does not return false after all substrings have been yielded.
Is this a Nim bug, or am I doing something wrong? Probably the latter, but the code works when I unroll the loop, which is puzzling.
I'd also like to have written the returned iterator without the for loop as just 'split(s)' but the compiler forbids it. Is there a locution to achieve that?
import strutils
proc makeIterator(s : string): iterator (): string =
result = iterator() : string =
for ss in split(s):
yield ss
when isMainModule:
let next = makeIterator("The quick brown fox jumped over the lazy dog.")
while not finished(next):
echo(next())
I'll have a deeper look later, but I'm pretty sure it's no bug, but the documentation really needs to be improved either way. finished HAS to be called after the iterator and if it returns 'true' the return value of 'next' needs to be discarded:
let next = makeIterator("The quick brown fox jumped over the lazy dog.")
while true:
let potentialValue = next()
if finished(next): break
echo potentialValue
This is an inherent limitation of the transformation algorithm of an iterator into a state machine; for instance, Lua has exactly the same problem.