[Python-ideas] Function composition (was no subject)

Koos Zevenhoven koos.zevenhoven at aalto.fi
Sun May 10 01:07:19 CEST 2015


On 10.5.2015 1:03, Gregory Salvan wrote:
> Nobody convinced by arrow operator ?
>
> like: arg -> spam -> eggs -> cheese
> or cheese <- eggs <- spam <- arg
>
>

I like | a lot because of the pipe analogy. However, having a new 
operator for this could solve some issues about operator precedence.

Today, I sketched one possible version that would use a new .. operator. 
I'll explain what it would do (but with your -> instead of my ..)

Here, the operator (.. or ->) would have a higher precedence than 
function calls () but a lower precedence than attribute access (obj.attr).

First, with single-argument functions spam, eggs and cheese, and a 
non-function arg:

arg->eggs->spam->cheese()   # equivalent to cheese(spam(eggs(arg)))
eggs->spam->cheese  # equivalent to lambda arg: cheese(spam(eggs(arg)))

Then if, spam and eggs both took two arguments; eggs(arg1, arg2), 
spam(arg1, arg2)

arg->eggs   # equivalent to partial(eggs, arg)
eggs->spam(a, b, c)   # equivalent to spam(eggs(a, b), c)
arg->eggs->spam(b,c)  # equivalent to spam(eggs(arg, b), c)

So you could think of -> as an extended partial operator. And this would 
naturally generalize to functions with even more arguments. The 
arguments would always be fed in the same order as in the equivalent 
function call, which makes for a nice rule of thumb. However, I suppose 
one would usually avoid combinations that are difficult to understand.

Some examples that this would enable:

  # Example 1
  from numpy import square, mean, sqrt
  rms = square->mean->sqrt  # I think this order is fine because it is not @

  # Example 2 (both are equivalent)
  spam(args)->eggs->cheese() # the shell-syntax analogy that Steven 
mentioned.

  # Example 3
  # Last but not least, we would finally have this :)
  some_sequence->len()
  some_object->isinstance(MyType)

-- Koos

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150510/55a35085/attachment.html>


More information about the Python-ideas mailing list