欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中的高階函數(shù)介紹

 更新時間:2015年04月10日 09:25:35   投稿:junjie  
這篇文章主要介紹了C#中的高階函數(shù)介紹,本文講解了接受函數(shù)、輸出函數(shù)、Currying(科里化)等內(nèi)容,需要的朋友可以參考下

介紹

我們都知道函數(shù)是程序中的基本模塊,代碼段。那高階函數(shù)呢?聽起來很好理解吧,就是函數(shù)的高階(級)版本。它怎么高階了呢?我們來看下它的基本定義:
1:函數(shù)自身接受一個或多個函數(shù)作為輸入
2:函數(shù)自身能輸出一個函數(shù)。  //函數(shù)生產(chǎn)函數(shù)
 
滿足其中一個就可以稱為高階函數(shù)。高階函數(shù)在函數(shù)式編程中大量應(yīng)用。c#在3.0推出Lambda表達(dá)式后,也開始慢慢使用了。
 
目錄
1:接受函數(shù)
2:輸出函數(shù)
3:Currying(科里化)

一、接受函數(shù)

為了方便理解,都用了自定義。

代碼中TakeWhileSelf 能接受一個函數(shù),可稱為高階函數(shù)。

復(fù)制代碼 代碼如下:

//自定義委托
    public delegate TResult Function<in T, out TResult>(T arg);

    //定義擴(kuò)展方法
    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;  //定義一個函數(shù)

            IEnumerable<int> q2 = myAry.TakeWhileSelf(predicate);  //

            foreach (var item in q2)
            {
                Console.WriteLine(item);
            }
            /*
             * output:
             * 1
             * 2
             * 3
             */
        }
    }

二、輸出函數(shù)

代碼中OutPutMehtod函數(shù)輸出一個函數(shù),供調(diào)用。

復(fù)制代碼 代碼如下:

var t = OutPutMehtod();  //輸出函數(shù)
            bool result = t(1);

            /*
             * output:
             * true
             */

  static Function<int, bool> OutPutMehtod()
        {
            Function<int, bool> predicate = (num) => num < 4;  //定義一個函數(shù)

            return predicate;
        }

三、Currying(科里化)

一位數(shù)理邏輯學(xué)家(Haskell Curry)推出的,連Haskell語言也是由他命名的。然后根據(jù)姓氏命名Currying這個概念了。

上面例子是一元函數(shù)f(x)=y 的例子。

那Currying如何進(jìn)行的呢? 這里引下園子兄弟的片段。

假設(shè)有如下函數(shù):f(x, y, z) = x / y +z. 要求f(4,2, 1)的值。

首先,用4替換f(x, y, z)中的x,得到新的函數(shù)g(y, z) = f(4, y, z) = 4 / y + z

然后,用2替換g(y, z)中的參數(shù)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元函數(shù)求值,這樣的替換會發(fā)生n次,注意,這里的每次替換都是順序發(fā)生的,這和我們在做數(shù)學(xué)時上直接將4,2,1帶入x / y + z求解不一樣。

        在這個順序執(zhí)行的替換過程中,每一步代入一個參數(shù),每一步都有新的一元函數(shù)誕生,最后形成一個嵌套的一元函數(shù)鏈。

        于是,通過Currying,我們可以對任何一個多元函數(shù)進(jìn)行化簡,使之能夠進(jìn)行Lambda演算。

         用C#來演繹上述Currying的例子就是:

復(fù)制代碼 代碼如下:

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;
 }

相關(guān)文章

最新評論