介紹
我們都知道函數是程序中的基本模塊,代碼段。那高階函數呢?聽起來很好理解吧,就是函數的高階(級)版本。它怎么高階了呢?我們來看下它的基本定義:
1:函數自身接受一個或多個函數作為輸入
2:函數自身能輸出一個函數。 //函數生產函數
滿足其中一個就可以稱為高階函數。高階函數在函數式編程中大量應用。c#在3.0推出Lambda表達式后,也開始慢慢使用了。
目錄
1:接受函數
2:輸出函數
3:Currying(科里化)
一、接受函數
為了方便理解,都用了自定義。
代碼中TakeWhileSelf 能接受一個函數,可稱為高階函數。
//定義擴展方法
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函數輸出一個函數,供調用。
/*
* 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的例子就是:
新聞熱點
疑難解答