How can I use a “yield” inside a function like a generator/iterator?
function results()
yield 1
yield 2
yield 3
}
How can I use a “yield” inside a function like a generator/iterator?
function results()
yield 1
yield 2
yield 3
}
Unlike in Python, there is no “yielding iterator” built into Julia. yield
in Julia means the currently running task yields to the scheduler, so that other tasks can run.
Hi! Do you want to mimic the behavior from Python? E.g.
def results():
yield 1
yield 2
yield 3
Julia doesn’t support the same syntax as far as I know. You could write the same thing as
(i for i in 1:3)
and more complicated things as
(
begin
...
end
for i in ...
)
Not sure if there are other short ways of manually creating generator objects, besides the comprehension syntax? It’s a bit less convenient than the Python syntax in my opinion, but one can write a lot of generators like this as well.
The yield
function does something else as @Sukera already mentioned.
There is JuliaDynamics/ResumableFunctions.jl: C# style generators a.k.a. semi-coroutines for Julia. (github.com), but it is not ideal for performance critical tasks.
True, but if the comparison point is Python’s yield this likely isn’t a big deal
Breaking this down one step at a time. Julia is not Python, terms mean different things, and analogous concepts aren’t one-to-one.
nothing
.julia> function results()
Channel{Int}(function (channel) # schedules a task
for i in 1:3
put!(channel, i); println("round $i")
end
end)
end
results (generic function with 1 method)
julia> r = results()
Channel{Int64}(0) (1 item available)
julia> iterate(r, nothing) # take!(r) is idiomatic
round 1
(1, nothing)
julia> iterate(r, nothing)
round 2
(2, nothing)
julia> iterate(r, nothing)
round 3
(3, nothing)
julia> iterate(r, nothing) # take!(r) errors like Python here
julia> mutable struct Results state::Int end
julia> Results() = Results(0)
Results
julia> function Base.iterate(results::Results, state=nothing)
results.state += 1
if results.state <= 3
println("round $(results.state)"); return (results.state, nothing)
else
return nothing
end
end
julia> r = Results()
Results(0)
julia> iterate(r, nothing)
round 1
(1, nothing)
julia> iterate(r, nothing)
round 2
(2, nothing)
julia> iterate(r, nothing)
round 3
(3, nothing)
julia> iterate(r, nothing)