In functional programming, currying is a way to bind arguments with a function and wait for the rest of the arguments to show up later. You "curry in" the first few parameters to a function, giving you a function that takes subsequent parameters as input and calls the original with all of those parameters. This recipe uses a class instance to hold the parameters before their first use. For example:
Python, 14 lines
A typical use of curry is to construct callback functions for GUI operations. When the operation does not really merit a new function name, curry can be useful in creating these little functions. This can be the case with commands for buttons, for example.
self.button = Button(frame, text='A', command=curry(transcript.append, 'A'))
Curry can also be used interactively by making versions of your functions with debugging-appropriate defaults or initial parameters filled in for your current case. For example, database debugging work might well begin by setting:
If you are creating a function for regular use, and there is a good choice for a name, the 'def fun(...' form of function definition is usually more readable, and often more easily extended. As you can see from the implementation, no magic happens to "specialize" the function with the provided parameters; curry should be used when you feel the code is more clear with its use than without. Typically this will be to emphasize that you are only providing parameters to a "commonly used" (in this application) function, not providing separate processing.