I'm trying to pass an iterator to a proc, the way I pass a generator in Python. I've submitted a bug: https://github.com/nim-lang/Nim/issues/12487
I have a feeling it's not really a bug, and I'm just doing it wrong. I have searched this Forum, but nothing I've found has worked. Any ideas?
This seems to work for me:
template toClosure*(i): auto =
iterator j: type(i) {.closure.} =
for x in i:
yield x
j
iterator countUp(i, j: int): int =
for g in i..<j:
yield g
proc takeInCountUp(iter: iterator) =
for j in iter():
echo j
takeInCountUp(toClosure(countUp(0, 100)))
So it's likely there is something else going on.
Hmm. This works too:
import typetraits
template toClosure*(i): auto =
iterator j: type(i) {.closure.} =
for x in i:
yield x
j
iterator countUp(i, j: int, k: var string): int =
for g in i..<j:
k = $g
yield g
proc takeInCountUp(iter: iterator, k: var string) =
for j in iter():
echo j, " $", k
var hello = "world"
var x = toClosure(countUp(0, 3, hello))
echo "type:", x.type.name
takeInCountUp(x, hello)
type:iterator (): int{.closure, locks: 0.}
0 $0
1 $1
2 $2
And actually, I thought my original code was working for me, and then suddenly stopped for no apparent reason. I couldn't reproduce the original, so I figured I my mind was playing tricks on me.
There might be a subtle compiler bug.