In Julia, when looping through an iterable object I
is done with the for
syntax:
for i = I # or "for i in I" # body end
Behind the scenes, this is translated to:
state = start(I) while !done(I, state) (i, state) = next(I, state) # body end
Therefore, if you want I
to be an iterable, you need to define start
, next
and done
methods for its type. Suppose you define a type Foo
containing an array as one of the fields:
type Foo bar::Array{Int,1} end
We instantiate a Foo
object by doing:
julia> I = Foo([1,2,3])
Foo([1,2,3])
julia> I.bar
3-element Array{Int64,1}:
1
2
3
If we want to iterate through Foo
, with each element bar
being returned by each iteration, we define the methods:
import Base: start, next, done start(I::Foo) = 1 next(I::Foo, state) = (I.bar[state], state+1) function done(I::Foo, state) if state == length(I.bar) return true end return false end
Note that since these functions belong to the Base
module, we must first import
their names before adding new methods to them.
After the methods are defined, Foo
is compatible with the iterator interface:
julia> for i in I println(i) end 1 2 3