# 拿 C# 搞函数式编程

C# 有委托，而且有 Func<> 和 Action<>，可以说函数被视为一等公民，跟 int、bool 等类型并没有什么区别。那么很多事情就简单了。

## 柯里化

`var function = new Func<int, int, int>    ((x, y) => x + y);function(1, 2); // returns 3`

`function 1 2`

`function(1)(2);`

`Func<int, Func<int, int>> Currying(Func<int, int, int> f)    => x => y => f(x, y);`

`public static class CurryingExtensions{    public static Func<int, Func<int, int>>         Currying(this Func<int, int, int> f)            => x => y => f(x, y);}`

`var function = new Func<int, int, int>    ((x, y) => x + y)    .Currying();function(1)(2); // returns 3`

`public static class CurryingExtensions{    public static Func<T1, Func<T2, TOutput>>         Currying<T1, T2, TOutput>(this Func<T1, T2, TOuput> f)            => x => y => f(x, y);}`

## 高阶函数

var happyWater = new Func<float, int, float>

((float price, int number) => number * price)

.Currying();

// 调用：happyWater(快乐水单价)(快乐水件数);

var cocaHappyWater = happyWater(3.5f);

var pepsiHappyWater = happyWater(3);

var mcdHappyWater = happyWater(9);

`var calcPrice = new Func<Func<int, float>, float, int, float>    ((calc, discount, number) => discount * calc(number))    .Currying();// 调用：calcPrice(快乐水价格计算函数)(超市折扣)(快乐水件数);`

`var pepsiPriceCalc = calcPrice(pepsiHappyWater);var cocaPriceCalc = calcPrice(cocaHappyWater);var priceCalcA = pepsiPriceCalc(1); // A 超市var priceCalcB = cocaPriceCalc(0.8f); // B 超市`

`var priceA = priceCalcA(3);var priceB = priceCalcB(5);var total = priceA + priceB;`

`原文链接：https://www.cnblogs.com/hez2010/p/11487006.html.NET社区新闻，深度好文，欢迎访问公众号文章汇总 http://www.csharpkit.com `