genexp reduce syntax in 2.5a1

B

Boris Borcic

On the python3000 mailing list there was some discussion of a "comprehension
syntax" for reduce.

This inspired me the following proof-of-concept in pure python 2.5a1, although I
don't know if it relies on an intended feature or a(n unintended) bug.

Cheers, BB
--

def ireduce(gen) :
"""
Generator expression syntax for reduce and generalizations

Usage examples:

- (yield) nothing as below if there is no seed value
*and* the expression consists of a single arithmetic op
120

- if there is a seed, yield it (unless it's None)
0

- if the seed is None, (yield INone) instead
('men', ('good', ('all', ('for', None))))
>>> ireduce([(yield INone),x] for x in "for all good men".split())
[[[[None, 'for'], 'all'], 'good'], 'men']

- do as below if you want no special seed and the operation to reduce
isn't a simple arithmetic operation
('men', ('good', ('all', 'for')))
'men good all for'
{'men': {'good': {'all': 'for'}}}

- and notice these for a comparison
{'men': {'good': {'all': {'for': 'for'}}}}
{'men': {'good': {'all': None}}}
"""

cumulate = gen.next()
if cumulate is None :
cumulate = Neutral()
elif cumulate is INone :
cumulate = None
elif isinstance(cumulate,Seed) :
cumulate = cumulate.seed
gen.send(cumulate)
gen.next()
try :
while True :
cumulate = gen.send(cumulate)
gen.next()
except StopIteration :
return cumulate

class Neutral :
def __coerce__(self,other) :
self.other = other
return (self,self)

def __getattr__(self,attr) :
return lambda *x,**y : self.__dict__['other']

class INone : pass

class Seed :
def __init__(self,seed) :
self.seed = seed
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top