[Python-Dev] Re: accumulator display syntax
Nick Coghlan
ncoghlan at iinet.net.au
Fri Oct 24 08:18:14 EDT 2003
Guido van Rossum strung bits together to say:
>>I had a similar thought about 5 minutes after turning my computer off last
>>night. The alternative I came up with was:
>>
>> y = (from result = 0.0 do result += x**2 for x in values if x > 0)
>
>
> I think you're aiming for the wrong thing here; I really see no reason
> why you'd want to avoid writing this out as a real for loop if you
> don't have an existing accumulator function (like sum()) to use.
One interesting thing is that I later realised that iterator comprehensions
combined with the sum function would actually cover 90% of the accumulation
functions I would ever write.
So Raymond turns out to be correct when he suggests that generator expressions
may limit the need for reduce functions and accumulation loops. With the sum()
built in around, they will cover a large number of the reduction operations
encountered in real life. Previously, sum() was not available, and even if it
had been the cost of generating the entire list to be summed may have been
expensive (if the values to be summed are a function of the stored values,
rather than a straight sum).
So while I think a concise reduction syntax was worth aiming for, I'm also
willing to admit that it seems to be basically impossible to manage without
violating Python's maxim of "one obvious way to do it". The combination of
generator expressions and the various builtins that operate on iterables
(especially sum()) is a superior solution.
Still, I learned a few interesting things I didn't know last week :)
Cheers,
Nick.
--
Nick Coghlan | Brisbane, Australia
ICQ#: 68854767 | ncoghlan at email.com
Mobile: 0409 573 268 | http://www.talkinboutstuff.net
"Let go your prejudices,
lest they limit your thoughts and actions."
More information about the Python-Dev
mailing list