Confessions of a Python fanboy
Terry Reedy
tjreedy at udel.edu
Fri Jul 31 12:24:28 EDT 2009
Masklinn wrote:
> #each is simply a method that takes a function (called blocks in ruby).
> One could call it a higher-order method I guess.
>
> It's an implementation of the concept of internal iteration: instead of
> collections yielding iterator objects, and programmers using those
> through specially-built iteration constructs (e.g. `for…in`),
> collections control iteration over themselves (the iteration is
> performed "inside" the collection, thus the "internal" part) and the
> programmer provides the operations to perform at each iterative step
> through (usually) a function.
Python's iterator protocol was developed in part to avoid the
(inside-out) callback style of programming. Writing virtual collections
as generator functions instead of iterator or iterable classes saves a
lot of boilerplate code. The itertools modules shows how nicely
iterators can be composed in a way that is much more awkward with callbacks.
> In Python (assuming we had anonymous defs and an each method on lists),
> the following loop:
>
> for item in some_list:
> do_something(item)
> do_something_else(item)
>
> some_list.each((def (item):
> do_something(item)
> do_something_else(item)
> ))
And how does Ruby do the equivalent of
def double(it):
for i in it:
yield 2*i
for i,j in zip(double(some_list), some_gen_func(args)):
print(do_something(i+j,i-j))
Terry Jan Reedy
More information about the Python-list
mailing list