Kristoffer Carlsson
2015-05-01 19:07:03 UTC
Hello everyone,
I have what is likely a basic question about iterators in Julia.
Let's say I want to implement an iterator over a vector of objects and only
return (or yield) the objects that have some sort property.
Initially I tried something like this:
immutable MyIter{T}
v::Vector{T}
end
Base.start() = 1
Base.done(::MyIter, state) = state > length(v)
function Base.next(myiter::MyIter, state)
if has_property(v[state])
return(v[state], state+1)
else
return(next(myiter, state+1))
end
This does not work because when I hit the last element with the property
the iterator will go into an infinite loop. It feels like I have to check
if there are any more elements
left with the property in the done function but then I have to iterate over
the rest of the vector...
What I basically want is in my next function to be able to say "No more
items to return, stop iterating". In Python I would just yield the value
when the property is true and raise StopIterating when I reach the end of
the vector. Can I do something similar in Julia?
Best regards,
Kristoffer Carlsson
I have what is likely a basic question about iterators in Julia.
Let's say I want to implement an iterator over a vector of objects and only
return (or yield) the objects that have some sort property.
Initially I tried something like this:
immutable MyIter{T}
v::Vector{T}
end
Base.start() = 1
Base.done(::MyIter, state) = state > length(v)
function Base.next(myiter::MyIter, state)
if has_property(v[state])
return(v[state], state+1)
else
return(next(myiter, state+1))
end
This does not work because when I hit the last element with the property
the iterator will go into an infinite loop. It feels like I have to check
if there are any more elements
left with the property in the done function but then I have to iterate over
the rest of the vector...
What I basically want is in my next function to be able to say "No more
items to return, stop iterating". In Python I would just yield the value
when the property is true and raise StopIterating when I reach the end of
the vector. Can I do something similar in Julia?
Best regards,
Kristoffer Carlsson