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))))
- 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
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))))
[[[[None, 'for'], 'all'], 'good'], 'men']>>> ireduce([(yield INone),x] for x in "for all good men".split())
- 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