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 11:32:53 EST 2010


On Feb 19, 7:50 am, Roald de Vries <r... at roalddevries.nl> wrote:
> > This pipeline idea has actually been implemented further, see <http://
> > blog.onideas.ws/stream.py>.
>
> > from stream import map, filter, cut
> > range(10) >> map(lambda x: [x**2, x**3]) >> filter(lambda t: t[0]!
> > =25 and t[1]!=64) >> cut[1] >> list
> > [0, 1, 8, 27, 216, 343, 512, 729]
>
> Wow, cool!
>
> Just to show that you can easily add the iterator.map(f).blabla-syntax  
> to Python:
>
>      from __future__ import print_function
>
>      class rubified(list):
>          map    = lambda self, f: rubified(map(f, self))
>          filter = lambda self, f: rubified(filter(f, self))
>          reject = lambda self, f: rubified(filter(lambda x: not f(x),  
> self))
>          # each = lambda self, f: rubified(reduce(lambda x, y:  
> print(y), self, None))
>          def each(self, f):
>              for x in self: f(x)
>
>          def __new__(cls, value):
>              return list.__new__(cls, value)
>
>      def print_numbers():
>          rubified([1, 2, 3, 4, 5, 6]).map(lambda n:
>              [n * n, n * n * n]).reject(lambda (square, cube):
>              square == 25 or cube == 64).map(lambda (square, cube):
>              cube).each(lambda n:
>              print(n))

Sure, that definitely achieves the overall sequential structure of
operations that I like in Ruby.  A couple other example have been
posted as well now, which also mimic something akin to a Unix
pipeline.

A lot of Ruby that I see gets spelled like this:

   list.select { |arg1, arg2|
      expr
   }.reject { |arg|
      expr
   }.collect { |arg}
      expr
   }

With your class you can translate into Python as follows:

   list.select(lambda arg1, arg2:
      expr
   ).reject(lambda arg:
      expr
   ).collect(lambda arg:
      expr
   )

So for chaining transformations based on filters, the difference
really just comes down to syntax (and how much sugar is built into the
core library).

The extra expressiveness of Ruby comes from the fact that you can add
statements within the block, which I find useful sometimes just for
debugging purposes:

    debug = true
    data = strange_dataset_from_third_party_code()
    data.each { |arg|
        if debug and arg > 10000
            puts arg
        end
        # square the values
        arg * arg
    }







More information about the Python-list mailing list