i was reading in the Discourse Slack when someone asked about some syntax equivalent to the yield
keyword in python. in Julia, the syntax ´for i in iter´ is lowered to iterate(iter::IterType)
and iterate(iter::IterType,state)
, from the docs:
for i in iter # or "for i = iter" # body end
is translated into:
next = iterate(iter) while next !== nothing (i, state) = next # body next = iterate(iter, state) end
so the interface requires the existence of a type IterType
and the definition of iterate
over that type.
The yield
keyword does something weird that probably involves internal state, but is very convenient to do, and only requires the definition of a function. compare this (from Stack Overflow):
def squares(n):
mylist = range(n)
for i in mylist:
yield i*i
to this (from Julia Docs):
struct Squares
count::Int
end
Base.iterate(S::Squares, state=1) = state > S.count ? nothing : (state*state, state+1)
so, in the context of Julia, how can an anonymous iterator can be done?