Partial application and closures

前端 未结 5 1134
独厮守ぢ
独厮守ぢ 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:21

    Partial application is a technique whereby you take an existing function and a subset of it's arguments, and produce a new function that accepts the remaining arguments.

    In other words, if you have function F(a, b), a function that applies partial application of a would look like B(fn, a) where F(a, b) = B(F, a)(b).

    In your example you're simply creating new functions, rather than applying partial application to the existing one.

    Here's an example in python:

    def curry_first(fn, arg):
        def foo(*args):
           return fn(arg, *args)
        return foo
    

    This creates a closure over the supplied function and argument. A new function is returned that calls the first function with new argument signature. The closure is important - it allows fn access to arg. Now you can do this sort of thing:

    add = lambda x, y : x + y;
    add2 = curry_first(add, 2)
    add2(4) # returns 6
    

    I've usually heard this referred to as currying.

提交回复
热议问题