|
> Message: 7 > Date: Mon, 16 Dec 2013 14:46:10 -0500 > From: Tom N Harris <telliamed@whoopdedo.org> > Subject: Re: Hi, I am a little confused about stateless iterator. > To: lua-l@lists.lua.org > Message-ID: <1431849.AMzBL4T3Ev@green> > Content-Type: text/plain; charset="us-ascii" > > Your stateful function is wrong. It's stateful because the iterator keeps a > private state. This means the third value, the initial state, is not used. The > version you wrote will be invoked with i=0 the first time, then i=min, then > i=min+min, etc. > > Fixed version is: > > > --stateful > > --[[ > > function fromto(n,m) > > local r = m - n > > local i = -1 > > return function() > > i = i + 1 > > if i < r then > > return n + i > > else > > return nil > > end > > end > > end > > --]] > > Your stateless iterator is correct. The function receives the state variable > from the invoker which it mutates then passes back. Each time the iterator > receives the result of the previous iteration, which is suitable when each > element in the sequence is derived from the previous element. If you need more > state than what the iterator returns, you need to be stateful. For instance, > you couldn't generate a Fibonacci sequence with a stateless iterator. No, > that's not true. But it would look like: > > for _,n in fibonacci() do print(n) end > > Where _ is a table or closure. But if you're going to create the garbage > anyway, you may as well make the iterator a closure. Thanks for your explanation. |