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

Andrew Barnert abarnert at yahoo.com
Sun May 10 00:49:22 CEST 2015


On May 9, 2015, at 11:33, Donald Stufft <donald at stufft.io> wrote:
> 
> 
>> On May 9, 2015, at 2:30 PM, David Mertz <mertz at gnosis.cx> wrote:
>> 
>>> On Sat, May 9, 2015 at 1:16 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>> On Sat, May 09, 2015 at 11:38:38AM -0400, Ron Adam wrote:
>>> 
>>> > How about an operator for partial?
>>> >
>>> >           root @ mean @ map $ square(xs)
>> 
>> I have trouble seeing the advantage of a special function composition operator when it is easy to write a general 'compose()' function that can produce such things easily enough.
>> 
>> E.g. in a white paper I just did for O'Reilly on _Functional Programming in Python_ I propose this little example implementation:
>> 
>> def compose(*funcs):
>>     "Return a new function s.t. compose(f,g,...)(x) == f(g(...(x)))"
>>     def inner(data, funcs=funcs):
>>         result = data
>>         for f in reversed(funcs):
>>             result = f(result)
>>         return result
>>     return inner
>> 
>> Which we might use as:
>> 
>>   RMS = compose(root, mean, square)
>>   result = RMS(my_array)
> 
> 
> Maybe functools.compose?

But why?

This is trivial to write.

The nontrivial part is thinking through whether you want left or right compose, what you want to do about multiple arguments, etc. So, unless we can solve _that_ problem by showing that there is one and only one obvious answer, we don't gain anything by implementing one of the many trivial-to-implement possibilities in the stdlib.

Maybe as a recipe in the docs, it would be worth showing two different compose functions to demonstrate how easy it is to write whichever one you want (and how important it is to figure out which one you want).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150509/044c541b/attachment.html>


More information about the Python-ideas mailing list