[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: "Generators" in Python (and C!) (was Re: "Python for Lisp Programmers")
At 10:59 AM 12/9/2001 -0500, Eric Kidd wrote:
>On Sun, 2001-12-09 at 03:35, Michael Vanier wrote:
> > Having been out of the perl loop for some time, I'm curious about this.
> > How does perl support iterators?
>
>In much the same fashion as C++ or Java.
Yup, they're implemented in C! :)
Seriously, perl's got two ways to do iterators. (We don't formally have
coroutines, though we could fake it simply enough with one of perl's
threading implementations. The parrot engine will support coroutines
correctly without threads as soon as I sort out how to handle unhandled
exceptions)
Hashes have had, essentially always, had a simple iterator attached to
them. Call each on a hash and you get the next hash key, or key/value pair.
Pretty trivial.
For more complex things you can either go with the function call route that
has a state param (which you can manually track, or use perl source filters
to do a variant on the Duff's Device trick that Eric appended) or go with
the more general, and more perlish, active data route.
For that you'd have a module that provides your next value in the form of
an active variable. The underlying code's a bit big since the active data
interface is pretty general, but the end result is your progrm looks like:
$iter = ArrayIter::make_iter(\@foo);
and every lvalue use of $iter calls the underlying FETCH method, which can
do whatever it needs, in this case fetching the next entry in the array.
(Or anything else you might want, folks use the interface to attach hashes
to disk files to make them persistent, or tie scalars to hardware to either
monitor or control it) You still need to write the actual iteration code,
but there are modules on CPAN that do this already.
Dan
--------------------------------------"it's like this"-------------------
Dan Sugalski even samurai
dan@sidhe.org have teddy bears and even
teddy bears get drunk