Hello,
PyGen - python style generators - #17 by nsmith and Creating Generators introduce how to mimics Python generator with Julia Channel.
With Python, a generator can be used like an iterator with next
function (or __next__
method)
In [1]: def gen():
...: for i in range(10):
...: yield i
...:
In [2]: for i in gen():
...: print(i)
...:
0
1
2
3
4
5
6
7
8
9
In [3]: g = gen()
In [4]: next(g) # or g.__next__()
Out[4]: 0
In [5]: next(g)
Out[5]: 1
In [6]: next(g)
Out[6]: 2
In [7]: next(g)
Out[7]: 3
In [8]: next(g)
Out[8]: 4
In [9]: next(g)
Out[9]: 5
In [10]: next(g)
Out[10]: 6
In [11]: next(g)
Out[11]: 7
In [12]: next(g)
Out[12]: 8
In [13]: next(g)
Out[13]: 9
In [14]: next(g)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-14-5f315c5de15b> in <module>()
----> 1 next(g)
StopIteration:
I wonder if a Julia generator implemented using Channel can be used like an iterator (ie have a next
function implementation)
julia> gen() = Channel(ctype=Int) do c
for i in 0:10-1
push!(c, i)
end
end
gen (generic function with 1 method)
julia> g = gen()
julia> for i in g
println(i)
end
0
1
2
3
4
5
6
7
8
9
Unfortunatelly it doesn’t work as expected:
julia> g = gen()
julia> state = start(g)
Base.ChannelIterState{Int64}(false, 0)
julia> i, state = next(g, state)
(0, Base.ChannelIterState{Int64}(false, 0))
julia> i, state = next(g, state)
(0, Base.ChannelIterState{Int64}(false, 0))
julia> i, state = next(g, state)
(0, Base.ChannelIterState{Int64}(false, 0))
Any idea why it’s behaving this way?
Kind regards