Partial application and closures

前端 未结 5 1133
独厮守ぢ
独厮守ぢ 2021-02-14 06:36

I was asked what\'s the relationship between partial function application and closures. I would say there isn\'t any, unless I\'m missing the point. Let\'s say I\'m writing in p

5条回答
  •  灰色年华
    2021-02-14 07:27

    Partial function application is about fixing some arguments of a given function to yield another function with fewer arguments, like

    sum = lambda x, y: x + y
    inc = lambda x: sum(x, 1)
    

    Notice that 'inc' is 'sum' partially applied, without capturing anything from the context (as you mentioned closure).

    But, such hand-written (usually anonymous) functions are kind of tedious. One can use a function factory, which returns an inner function. The inner function can be parameterized by capturing some variable from its context, like

    # sum = lambda x, y: x + y
    def makePartialSumF(n):
        def partialSumF(x):
            return sum(x, n)
        return partialSumF
    
    inc = makePartialSumF(1)
    plusTwo = makePartialSumF(2)
    

    Here the factory makePartialSumF is invoked twice. Each call results in a partialSumF function (capturing different values as n). Using closure makes the implementation of partial application convenient. So you can say partial application can be implemented by means of closure. Of course, closures can do many other things! (As a side node, python does not have proper closure.)

    Currying is about turning a function of N arguments into a unary function which returns a unary function... for example we have a function which takes three arguments and returns a value:

    sum = lambda x, y, z: x + y + z
    

    The curried version is

    curriedSum = lambda x: lambda y: lambda z: x + y + z
    

    I bet you wouldn't write python code like that. IMO the motivation of Currying is mostly of theoretical interest. (A framework of expressing computations using only unary functions: every function is unary!) The practical byproduct is that, in languages where functions are curried, some partial applications (when you 'fix' arguments from the left) are as trivial as supplying arguments to curried function. (But not all partial applications are as such. Example: given f(x,y,z) = x+2*y+3*z, when you binds y to a constant to yield a function of two variables.) So you can say, Currying is a technique which, in practice and as a byproduct, can make many useful partial functional applications trivial, but that's not the point of Currying.

提交回复
热议问题