Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #9832 > unrolled thread

Re: Partial Function Application -- Advantages over normal function?

Started byTerry Reedy <tjreedy@udel.edu>
First post2011-07-18 15:58 -0400
Last post2011-07-18 15:58 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Partial Function Application -- Advantages over normal function? Terry Reedy <tjreedy@udel.edu> - 2011-07-18 15:58 -0400

#9832 — Re: Partial Function Application -- Advantages over normal function?

FromTerry Reedy <tjreedy@udel.edu>
Date2011-07-18 15:58 -0400
SubjectRe: Partial Function Application -- Advantages over normal function?
Message-ID<mailman.1229.1311019143.1164.python-list@python.org>
On 7/18/2011 8:24 AM, Paul Woolcock wrote:
> Partial function application (or "currying") is the act of taking a
> function with two or more parameters, and applying some of the arguments
> in order to make a new function.  The "hello world" example for this
> seems to be this:
>
> Let's say you have a function called `add`, that takes two parameters:
>
>> >> def add(left, right):
>      ...     return left + right
>
> Now let's say you want a function that always adds 2 to a number you
> give it.  You can use partial function application to do this:
>
>  >>> from functools import partial
>  >>> add2 = partial(add, right=2)
>
> Now, you have a new function, `add2`, that takes one parameter:
>
>  >>> add2(4)

Or you can directly write

def add2(x): return x + 2

or more generically

def makeadder(y)
     def _add(x): return x+y
add2 = makeadder(2)

functool.partial is essential a generic version of makeadder in that it 
also abstract the function/operator. It is useful when one has a 
function but perhaps not the source. It's limitation is that args are 
frozen left to right while the above example freezes the right operand.

-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web