Partial application is a programming technique for passing less than the full number of arguments to a function, in order to yield a new function that can be used later. It is particularly common in functional languages that support currying.
Partial application is a programming technique for passing less than the full number of arguments to a function, in order to yield a new function that can be used later. It is particularly common in functional-programming languages that support currying.
Example (OCaml)
(* `add` is a function with arity 2 *)
let add a b = a + b
(* `add` is partially applied with the arguemnt `2`,
* yielding a function of arity 1 *)
let add2 = add 2
(* `4` is applied to `add2`, making it fully applied
* and yielding the result of evaluating `add`: `6` *)
let x = add2 4
Example (Python)
Consider the following function:
def add_together(a, b):
return a + b
If we want to hold a
constant, we can manually create the same function with a constant, for example, 5
:
def add_together(b):
return 5 + b
In programming, we typically want a programmatic way of setting our constant and generating our partial function. In Python, we can do this with a closure:
def set_a_on_add_together(a): # the outer function takes a parameter, a
def add_a_to(b): # outer function def's new function w/ parameter, 5
return a + b # the new function returns a, held constant, plus b
return add_a_to # outer function returns the newly created function
and would be used like this:
add_to_five = set_a_on_add_together(5)
add_to_five(4)
would return 9
, and
add_to_five(10)
would return 15
.