On 31 Jul 2009, at 18:24 , Terry Reedy wrote:
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))
Somethign along the lines of
some_list.map{|e| 2*e}.zip(some_gen_func(args)).each {|i, j|
puts(do_something(i+j, i-j))
}
The `#each` call after `#zip` is not actually necessary, but I find it
clearer. Oh, and some_gen_func and do_something probably wouldn't work
that way (as I said above, Ruby isn't big on named functions and
doesn't actually have them)
--
http://mail.python.org/mailman/listinfo/python-list