[Python-ideas] Rehabilating reduce (as "fold")

Andrew Barnert abarnert at yahoo.com
Fri Jul 12 18:39:18 CEST 2013


On Jul 12, 2013, at 3:36, Haoyi Li <haoyi.sg at gmail.com> wrote:

> I would much prefer the somewhat-more-difficult route of modifying the parser to let `a += b` be an expression, and then you could write
> 
> data = fold(lambda a, b: a += b, [], iterables)

But that doesn't really _mean_ anything as an expression; it's pure side effect. Besides, if that returns the new a then it invites all the expression order problems from C and friends that Python has always escaped; if it returns None, the fold doesn't actually work.

Meanwhile, the way you wrote it:

> `a += b`

Reminds me. We took away backticks for repr; what about using them for quoting operators? `+=` says "quoting" in the lisp sense more loudly than the PHP sense... At least to me. And this means fold wouldn't need to accept a string; it's getting a function.

Of course it's the exact opposite of Haskell, where you use backticks to turn a function into an operator and parens to turn an operator into a function. 

> or even groovy/scala/mathematica style
> 
> data = fold(_ += _, [], iterables)

I semi-suggested this elsewhere, but without the magic of guessing whether two underscores meant the same arg twice or two different args (so you'd have to write _1 == _2 or similar).

You can actually write functions this way today using an expression template library, without macros or anything:

    class Expr:
        def __init__(self, f=identity)
            self.f = f
        def __iadd__(self, other):
            return Expr(compose(iadd, self.f))
        def __call__(self, *args):
            return self.f(*args)

    _1, _2 = Expr(), Expr()

Actually, this silly proof of concept _would_ work with _ for both args, but only because it won't work for much else (even adding literals).

Anyway, while you can do this, I'm not sure you should. Boost.Lambda had this kind of magic, and nobody proposed it for C++11 when real lambdas were added, because it's a clumsy fit for a language that wasn't designed for it from the start--you end up needing const, var, and ref functions to paper over the gaps where overloading doesn't quite get you there, and horrible workarounds for the operators that can't be overloaded, ...

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130712/d335b0b1/attachment-0001.html>


More information about the Python-ideas mailing list