Yesterday, I
posted on
anonymous methods, the syntax to create them and how to use them to create a simple
closure. In a
previous post, I used an anonymous method to form a closure for the purposes of caching a result. This type of use is called
memoization. Today, I'd like to show a different type of use for a closure called
Currying.
"Currying" or "Schonfinkelization", named for
Haskell B Curry or
Moses Schonfinkel respectively, is a programming technique wherein a function is created which takes a function with multiple arguments and returns a function which will only take a single argument - the rest of the arguments having been bound to the returned function.
Interestingly, the idea was originally conceived by Schonfinkel but Curry's name is the one usually attached to the concept - it's rarely called "Schonfinkelization", Just do a Google search on the
two terms to see for yourself.
Here is an example of using an anonymous method to create a currying function:
As you can see, this generic Curry function takes a delegate type of Func<T, T2, TResult> - this is a function pointer for any function which takes two arguments and returns a value. The Curry function also takes a value which will be bound to the returned function. It returns a delegate type of Func<T, TResult> which represents any function which takes a single argument and returns a value.
Here is a test where we leverage the Curry function:
In this test, we use the Curry function to bind the Add function of the AdditionTheHardWay class to a variable - in this case the integer 90. This gives us a new function which is represented by the delegate addToX. We can later invoke this function pointer and provide it with a single argument to do our addition.