From: "Hal E. Fulton" Date: 2003-03-24T14:10:54+09:00 Subject: Re: Iteration styles (was Ruby lecture slides) ----- Original Message ----- From: "Jim Weirich" To: "ruby-talk ML" Sent: Sunday, March 23, 2003 10:52 PM Subject: Iteration styles (was Ruby lecture slides) [snip fascinating discussion] Thanks for saying all this so clearly and concisely, Jim. This should be captured somewhere. I have often felt the need for an external iterator in Ruby. (If I'm understand your terminology correctly.) Sometimes I want to "grab" the next item or next n items without tangling my logic. In that case, a traditional while loop with a counter works about as well as anything else. To me, being stuck using the built-in iterators for structures such as arrays is analogous to using *only* the iterators for files. Often I want to iterate through a file, just barrelling through it like a locomotive. But sometimes I want to grab a char or a line, or several of them, and proceed with my logic. The same with an array or tree or whatever. This was part of my motivation for my "super-iterator" that I posted several months ago. > This is possible in Ruby, but it requires that we be able to return from > a function in such a way we can resume the function at the return point > (exactly as generators do). We don't have generators in Ruby, but we do > have a very powerful, mind-bending capability called continuations. > Someday I would like to write up how do use continutations to do this, > but this note is already too long. Suffice it to say that we can use > continuations to implement generator capability in about 20 lines of > code. Does this remind anyone but me of Fermat's Last Theorem? :) > So, if we need external iterators AND we have a container class that > only provides internal iterators AND we don't want to duplicate the loop > iteration logic, THEN we can use generators (implemented in > continuations) to get the effect we want. That's fascinating. Could this be generalized to the point that given an object and its external iterator, we could just mix in a module to give us an external iterator? If so, I think this would be a worthwhile thing indeed. In fact, though it might be only 20 lines long or so, I would say it belongs in the RAA (if not in the core). > So which way is better? I find it is fascinating that both Ruby and > Python have almost equivalent power in its iteration, they have just > taken different paths to get there. I still want to learn Python. But it is nowhere near my list of the top twenty things I want to do. Cheers, Hal