What is the advantage of Currying in C#?
What is the advantage of achieving partial function application on a curried function?
What is the advantage of Currying in C#?
What is the advantage of achieving partial function application on a curried function?
From Wikipedia
Currying is actually not very different from what we do when we calculate a function for some given values on a piece of paper.
Take the function
f(x,y) = y / x
To evaluate
f(2,3)
, first, replacex
with2
.Since the result is a new function in y, this function g(y) can be defined as
g(y) = f(2,y) = y / 2
Next, replacing the
y
argument with3
,provides the result,
g(3) = f(2,3) = 3 / 2
.On paper, using classical notation, it's just that we seem to do it all at the same time. But, in fact, when replacing arguments on a piece of paper, it is done sequentially (i.e.partially). Each replacement results in a function within a function. As we sequentially replace each argument, we are currying the function into simpler and simpler versions of the original. Eventually, we end up with a chain of functions as in lambda calculus, where each function takes only one argument, and multi-argument functions are usually represented in curried form.
The practical motivation for currying is that very often the functions obtained by supplying some but not all of the arguments to a curried function (often called partial application) are useful; for example, many languages have a function or operator similar to plus_one. Currying makes it easy to define these functions.
The advantage of Currying in C# is that it allows C# developers to develop in a Functional Programming style.
Think about LINQ. A LINQ query allows you to pass in a method as a parameter:
someCollection.Where(x => x.someVal == 1);
x.someVal == 1
gets evaluated as a function and then Where
uses the return value in its own execution.
It's an example that most .NET 3 developers are familiar with, but few realize that they're dabbling in Function Programming. Without the ability to Curry, LINQ wouldn't be possible.
...hopefull that makes up for my smart-ass comment.
If your question was how to implement currying in C# , here is an example
public Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(Func<T1, T2, TResult> func)
{
return p1 => p2 => func(p1, p2);
}
Currying can be implemented in any language that supports closures(lambdas), and is useful for partial function application like in UI programming where all the input necessary for the execution of function isnt received, so a curried function is passed around with already received inputs captured in it.