Currying is not something that I have used before. I encountered it recently during my dive into functional programming. So what is it, and can it be done using Python?
I would describe Currying as a method to create specific functions by using a more generic function as base. If you are used to Object Oriented Programming (OOP) you can think of the generic function as the base class and the more specific function as the derived class. Let me show by example.
Think of a function that multiplies every element in a list with a given multiple. This function would require two input parameters, the list and the multiple. In Python this could look like:
Now, imagine that you often want to multiply each element by three. You can do this by calling 'multiplyListElements(3, list)'. Or you can use Currying:
Now multiplyListElements takes only one argument, the multiple to use, and returns a function f that takes the list as argument. It can be used like this:
Pretty neat! Now this was a very simple, pedagogic, example. But it is easy to imagine a generic method that takes more arguments and where Currying can be used as an alternative to create nice specific functions.
Bonus level. You can use an anonymous - lambda - function instead of defining 'f' inside the multiplyListElements function. If you do that it will look like this:
I would describe Currying as a method to create specific functions by using a more generic function as base. If you are used to Object Oriented Programming (OOP) you can think of the generic function as the base class and the more specific function as the derived class. Let me show by example.
Think of a function that multiplies every element in a list with a given multiple. This function would require two input parameters, the list and the multiple. In Python this could look like:
def multiplyListElements(multiple, list):
return [multiple*x for x in list]
Now, imagine that you often want to multiply each element by three. You can do this by calling 'multiplyListElements(3, list)'. Or you can use Currying:
def multiplyListElements(multiple):
def f(list):
return [multiple*x for x in list]
return f
Now multiplyListElements takes only one argument, the multiple to use, and returns a function f that takes the list as argument. It can be used like this:
>>> doubleElements = multiplyListElements(2)
>>> doubleElements([1,2,3,4])
[2, 4, 6, 8]
>>> tripleElements = multiplyListElements(3)
>>> tripleElements([1,2,3,4])
[3, 6, 9, 12]
Pretty neat! Now this was a very simple, pedagogic, example. But it is easy to imagine a generic method that takes more arguments and where Currying can be used as an alternative to create nice specific functions.
Bonus level. You can use an anonymous - lambda - function instead of defining 'f' inside the multiplyListElements function. If you do that it will look like this:
def multiplyListElements(multiple):
return lambda list: [multiple*x for x in list]
Kommentarer
Skicka en kommentar