Last active
February 7, 2023 22:30
-
-
Save Clemapfel/5987bd8ba77e0274689f618f28b2ccd6 to your computer and use it in GitHub Desktop.
Julia Complex Iterator Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Random | |
# The iterable instance | |
struct Iterable | |
_ids::Vector{Int64} | |
_other::Vector{String} | |
Iterable() = new(rand(Int64, 10), [Random.randstring(3) for i in 1:10]) | |
end | |
# Iterator, holds reference to instance | |
mutable struct ComplexIterator | |
instance::Ref{Iterable} | |
i::Int64 | |
id::Int64 | |
other::String | |
ComplexIterator(i, instance::Iterable) = new(instance, i, instance._ids[i], instance._other[i]) | |
end | |
# advance the iterator one step, updates its fields | |
function advance(iterator::ComplexIterator) | |
if iterator.i != length(iterator.instance[]._ids) | |
iterator.i += 1 | |
iterator.id = iterator.instance[]._ids[iterator.i] | |
iterator.other = iterator.instance[]._other[iterator.i] | |
end | |
return iterator | |
end | |
# Iterable: start iteration by returning a ComplexIterator instead | |
function Base.iterate(instance::Iterable) | |
return (ComplexIterator(1, instance), 1) | |
end | |
# Iterable: stop iteration | |
function Base.iterate(instance::Iterable, i::Int64) | |
if i == length(instance._ids) | |
return nothing | |
else | |
return (ComplexIterator(i + 1, instance), i + 1) | |
end | |
end | |
# iterator: start state | |
function Base.iterate(it::ComplexIterator) | |
return (it, 1) | |
end | |
# iterator: succesive steps | |
function Base.iterate(it::ComplexIterator, i::Int64) | |
if i == length(it.instance[]._ids) | |
return nothing | |
else | |
advance(it) # advancing updates fields so they can be accessed | |
return (it, i+1) | |
end | |
end | |
# usage | |
instance = Iterable() | |
for it in instance | |
println("Id: ", it.id) | |
println("Other: ", it.other) | |
end | |
""" | |
Output: | |
Id: -5199682371322551963 | |
Other: KxA | |
Id: 1963780643060477616 | |
Other: cfz | |
Id: -8038754947851161495 | |
Other: cRo | |
Id: -7086019444048395646 | |
Other: lie | |
Id: -5416162732659090528 | |
Other: w5V | |
Id: 6410769836315988433 | |
Other: xFV | |
Id: 76395605441795193 | |
Other: UN6 | |
Id: 4689883532029073831 | |
Other: O8W | |
Id: -5366039862844754873 | |
Other: QUS | |
Id: -5366039862844754873 | |
Other: QUS | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment