Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret this code [closed]

Tags:

c#

lambda

Please interpret this code :

public static Func<TInput1, TOutput> Curry<TInput1, TOutput>(this Func<TInput1, TOutput> f)
{
    return x => f(x);
}

OR

Func<Int32, Int32> SubtractOne = x => x - 1;

what is the name of these techniques?

like image 501
masoud ramezani Avatar asked Dec 07 '22 04:12

masoud ramezani


2 Answers

The first sample is effectively a no-op as the input function is already in curried form; it just adds an extra level of indirection to the call. If you're interested in currying then have a look at the information on Wikipedia as a starting point.

The second sample creates a lambda expression named SubtractOne which will subtract one from the argument it is passed.

like image 51
Greg Beech Avatar answered Dec 31 '22 11:12

Greg Beech


The first snippet would only make sense if accompanied by several similar overloads. It's probably just to complete a set of methods called Curry. This word comes from the name Haskell Curry and refers to the ability in a programming language (or library) to supply a subset of the required parameters to a function in order to obtain another function that accepts the rest of the functions. It's easier to understand with an example:

void Foo(int a, string b, bool c) { ... }

You can call this supplying all three parameters:

Foo(123, "hi", false);

But in currying, you can do this:

var foo123 = Foo(123);

It gives you back another function that takes the remaining two parameters, so we say that it "binds" the first parameter to the value 123. But if you can curry with the original function, you can curry with the new one:

var foo123Hi = foo123("hi");

And finally supply the last argument:

foo123Hi(false);

At last we have all three arguments and only now does our definition of Foo actually execute for real.

In many functional languages (unsurprisingly in the languages Haskell and Curry) this is built into the language. In C# it is not, although you can partly simulate it by providing a set of overloads such as:

Action<string, bool> Foo(int a)
{
    return (b, c) => Foo(a, b, c);
}

Action<bool> Foo(int a, string b)
{
    return c => Foo(a, b, c);
}

But this still isn't quite right, because in the first example the returned Action<string, bool> will not be directly curry-able.

So there are sometimes attempts to provide a currying library that will enable currying on any function.

But with a sufficiently simple lambda syntax it is not actually clear that any library solution will be that helpful. After all, a lambda is a very simple way to bind one parameter, as shown in the above examples. So I'm not sure how widely used a "Curry" method library would be. The => operator is clearer, less clunky, more powerful and readable, and already built-in.

like image 45
Daniel Earwicker Avatar answered Dec 31 '22 10:12

Daniel Earwicker