Interesting talk on Python vs. Ruby and how he would like Python to have just a bit more syntactic flexibility.

Steve Howell showell30 at yahoo.com
Fri Feb 19 06:35:48 CET 2010


On Feb 18, 7:58 pm, Paul Rubin <no.em... at nospam.invalid> wrote:
> Steve Howell <showel... at yahoo.com> writes:
> >> But frankly, although there's no reason that you _have_ to name the
> >> content at each step, I find it a lot more readable if you do:
>
> >> def print_numbers():
> >>     tuples = [(n*n, n*n*n) for n in (1,2,3,4,5,6)]
> >>     filtered = [ cube for (square, cube) in tuples if square!=25 and
> >> cube!=64 ]
> >>     for f in filtered:
> >>         print f
>
> > The names you give to the intermediate results here are
> > terse--"tuples" and "filtered"--so your code reads nicely.
>
> But that example makes tuples and filtered into completely expanded
> lists in memory.  I don't know Ruby so I've been wondering whether the
> Ruby code would run as an iterator pipeline that uses constant memory.
>

Running the following code would probably answer your question.  At
least in the case of Array.map and Array.reject, under my version of
Ruby, each block transforms the entire array before passing control to
the next block.

    def print_numbers()
        [1, 2, 3, 4, 5, 6].map { |n|
            puts 'first block', n
            [n * n, n * n * n]
        }.reject { |square, cube|
            puts 'reject', square
            square == 25 || cube == 64
        }.map { |square, cube|
            cube
        }.each { |cube|
            puts cube
        }
    end

    print_numbers()

But I'm running only version 1.8.7.  Version 1.9 of Ruby apparently
introduced something more akin to generators and Unix pipelines:

http://pragdave.blogs.pragprog.com/pragdave/2007/12/pipelines-using.html

I haven't tried them myself.





More information about the Python-list mailing list