C# lambda - curry usecases

后端 未结 6 1737
小蘑菇
小蘑菇 2021-01-31 12:04

I read This article and i found it interesting.

To sum it up for those who don\'t want to read the entire post. The author implements a higher order function named Curry

6条回答
  •  攒了一身酷
    2021-01-31 12:34

    Currying is used to transform a function with x parameters to a function with y parameters, so it can be passed to another function that needs a function with y parameters.

    For example, Enumerable.Select(this IEnumerable source, Func selector) takes a function with 1 parameter. Math.Round(double, int) is a function that has 2 parameters.

    You could use currying to "store" the Round function as data, and then pass that curried function to the Select like so

    Func roundFunc = (n, p) => Math.Round(n, p);
    Func roundToTwoPlaces = roundFunc.Curry()(2);
    var roundedResults = numberList.Select(roundToTwoPlaces);
    

    The problem here is that there's also anonymous delegates, which make currying redundant. In fact anonymous delegates are a form of currying.

    Func roundToTwoPlaces = n => Math.Round(n, 2);
    var roundedResults = numberList.Select(roundToTwoPlaces);
    

    Or even just

    var roundedResults = numberList.Select(n => Math.Round(n, 2));
    

    Currying was a way of solving a particular problem given the syntax of certain functional languages. With anonymous delegates and the lambda operator the syntax in .NET is alot simpler.

提交回复
热议问题