How to implement an iterator in Julia?
-
21-12-2019 - |
Question
I am trying to implement an iterator in Julia, but get an exception when the for-loop tries to call start
already.
Here is what I get (I ran include(...), then using RDF
):
julia> methods(start)
# 1 method for generic function "start":
start(graph::Graph) at /Users/jbaran/src/RDF.jl/src/RDF.jl:214
julia> for x in g
println(x)
end
ERROR: `start` has no method matching start(::Graph)
in anonymous at no file
The function definition in the RDF
module looks like this at the moment:
function start(graph::Graph)
return GraphIterator(collect(keys(graph.statements)), nothing, nothing, nothing, [], [])
end
Any idea what I am doing wrong?
Solution
Don't forget to specify Base.
- you are adding methods to an existing function.
module MyMod
type Blah
data
end
export Blah
Base.start(b::Blah) = 1
Base.done(b::Blah,state) = length(b.data) == state-1
Base.next(b::Blah,state) = b.data[state], state+1
end
using MyMod
x = Blah([1,2,3])
for i in x
println(i)
end
This works as of Julia 0.3.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow