使用Lambda實現遞迴

來源:互聯網
上載者:User

遞迴描述

fn(n)

if(n ==1) return 1
return n * f(n-1)

當然上面的n我們假定為不為零的正整數

在lambda語言中無法直接表示,請看

            Func<int, int> fn = n =>
{
if (n == 1)
return 1;
else
return fn(n - 1) * n;
};

看上去不錯。可惜不能運行。因為 return fn(n - 1) * n; 中的fn使用前沒有定義。fn在它代表lambda表達示之前是沒有辦法使用的。

如果寫成這樣的偽碼呢

lambda fn = n => (n==1)?1: n * self(n-1)

看起來不錯。但是self怎麼來呢,乾脆做參數傳進來。寫成下面偽碼

lambda fn = n, self => (n==1)?1: n * self(n-1)

好像是可以。用c#實現看看。

            Func<object, int, int> fn = (p, n) =>
{
var fnx = p as Func<object, int, int>;
if (n == 1)
{
return 1;
}
else
{
return fnx(p, n - 1) * n;
}
};

可以啦。由於c#不是動態語言,所以有一個轉換。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.