[Python-ideas] Add nullifier argument to functools.reduce?

Warren Weckesser warren.weckesser at gmail.com
Sat Aug 23 18:27:12 CEST 2014


On Sat, Aug 23, 2014 at 12:01 PM, Joshua Landau <joshua at landau.ws> wrote:

> On 23 August 2014 16:30, Warren Weckesser <warren.weckesser at gmail.com>
> wrote:
> > I'd like to add an additional optional argument to functools.reduce.
> > The argument is the "nullifier" of the reducing operation.  It is a value
> > such that function(nullifier, anything) returns nullifier.  For example,
> if
> > function(x, y) computes x*y, the nullifier is 0.  If function(x, y) is
> > the intersection of the sets x and y, the nullifier is the empty set.
> >
> > The argument would allow reduce to "short circuit" its calculation.
>  When
> > reduce encounters the nullifier, it can return immediately.  This can
> > provide
> > a significant improvement in performance in some cases.
>
> This hasn't been given a use-case and seems like needless complexity.
> It also seems far too magical. -1 for those reasons.
>


I guess "magical" is a matter of perspective ("Any sufficiently advanced
technology..." and all that).



>
> If its only purpose is to speed up "reduce" it seems like a very bad
> trade-off, as *everywhere else* has a new now-sanctioned behaviour to
> worry about.
>

I don't understand what you mean.  Could you elaborate?



>
> A better answer in my opinion would be something more like
> "reduce(..., stop_on=sentinel)". This could even allow more
> optimisations than your idea:
>
>     reduce(operator.mul, iterable, stop_on=0)
>     reduce(operator.add, iterable, stop_on=float("nan"))
>
>
Do you mean it would stop when the sentinel was encountered in iterable?
That wouldn't help in an example such as

    reduce(lambda x, y: x & y, [{1,2}, {3, 4}, {5, 6}], nullifier={})

The nullifier is the empty set, but the empty set does not occur in the
iterable.


 (Joshua, sorry for sending this to you again.  Forgot to "Reply all" the
first time.)


etc.
>
> I would be -0 on that, because there hasn't been a mentioned use-case.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140823/ed8c749d/attachment.html>


More information about the Python-ideas mailing list