Currying
Function currying is a specific kind of function transformation where we translate a single function that accepts multiple arguments into multiple functions that each accept a single argument.
e.g.:
1def sum(a):
2 def inner_sum(b):
3 return a + b
4 return inner_sum
5
6print(sum(1)(2))
1final_volume = box_volume(3, 4, 5)
2print(final_volume)
3
4def box_volume(length):
5 def box_volume_with_len(width):
6 def box_volume_with_len_width(height):
7 return length * width * height
8 return box_volume_with_len_width
9 return box_volume_with_len
10
11final_volume = box_volume(3)(4)(5)
12print(final_volume)
The sum function only takes a single input, a. It returns a new function that takes a single input, b. This new function when called with a value for b will return the sum of a and b.
Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument. Instead of taking all arguments at once, a curried function takes the first argument and returns a new function that takes the second argument, and so on, until all arguments are provided.
Key Concepts of Currying
- Transformation: Currying transforms a function with multiple parameters into a series of nested functions, each with a single parameter.
- Partial Application: Currying facilitates partial application, where you can fix a few arguments of the function and get a new function that takes the remaining arguments.
References
#cache #expensive #referential #optimal #transparent #memoization #store #function #dynamic #efficient #boot_dev #speed #optimization #algorithm #programming