介紹
- 函數自身接受一個或多個函數作為輸入。
- 函數自身能輸出一個函數,即函數生產函數。
閱讀目錄
- 接受函數
- 輸出函數
- Currying(科里化)
接受函數
為了方便理解,都用了自定義。
代碼中TakeWhileSelf 能接受一個函數,可稱為高階函數。
//自定義委托 public delegate TResult Function<in T, out TResult>(T arg); //定義擴展方法 public static class ExtensionByIEnumerable { public static IEnumerable<TSource> TakeWhileSelf<TSource>(this IEnumerable<TSource> source, Function<TSource, bool> predicate) { foreach (TSource iteratorVariable0 in source) { if (!predicate(iteratorVariable0)) { break; } yield return iteratorVariable0; } } } class Program { //定義個委托 static void Main(string[] args) { List<int> myAry = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; Function<int, bool> predicate = (num) => num < 4; //定義一個函數 IEnumerable<int> q2 = myAry.TakeWhileSelf(predicate); // foreach (var item in q2) { Console.WriteLine(item); } /* * output: * 1 * 2 * 3 */ } }
輸出函數
代碼中OutPutMehtod函數輸出一個函數,供調用。
var t = OutPutMehtod(); //輸出函數 bool result = t(1); /* * output: * true */ static Function<int, bool> OutPutMehtod() { Function<int, bool> predicate = (num) => num < 4; //定義一個函數 return predicate; }
Currying(科里化)
一位數理邏輯學家(Haskell Curry)推出的,連Haskell語言也是由他命名的。然后根據姓氏命名Currying這個概念了。
上面例子是一元函數f(x)=y 的例子。
那Currying如何進行的呢? 這里引下園子兄弟的片段。
假設有如下函數:f(x, y, z) = x / y +z. 要求f(4,2, 1)的值。
首先,用4替換f(x, y, z)中的x,得到新的函數g(y, z) = f(4, y, z) = 4 / y + z
然后,用2替換g(y, z)中的參數y,得到h(z) = g(2, z) = 4/2 + z
最后,用1替換掉h(z)中的z,得到h(1) = g(2, 1) = f(4, 2, 1) = 4/2 + 1 = 3
很顯然,如果是一個n元函數求值,這樣的替換會發生n次,注意,這里的每次替換都是順序發生的,這和我們在做數學時上直接將4,2,1帶入x / y + z求解不一樣。
在這個順序執行的替換過程中,每一步代入一個參數,每一步都有新的一元函數誕生,最后形成一個嵌套的一元函數鏈。
於是,通過Currying,我們可以對任何一個多元函數進行化簡,使之能夠進行Lambda演算。
用C#來演繹上述Currying的例子就是:
var fun=Currying(); Console.WriteLine(fun(6)(2)(1)); /* * output: * 4 */ static Function<int, Function<int, Function<int, int>>> Currying() { return x => y => z => x / y + z; }
參考 http://www.cnblogs.com/fox23/archive/2009/10/22/intro-to-Lambda-calculus-and-currying.html