ラムダ式で再帰

ラムダ式再帰呼び出しのサンプルです。

using System;

class Program {
    static void Main() {
        Func<int, int> fact = null;
        fact = n => {
            if (n == 0)
                return 1;
            else
                return n * fact(n - 1);
        };

        for (int i = 1; i < 10; i++)
            Console.WriteLine(fact(i));
    }
}

実行結果です。

1
2
6
24
120
720
5040
40320
362880

fact 変数を null で初期化しています。 そうしないと、ラムダ式の中で自身の変数が参照できず、コンパイルエラーになります。

Func<int, int> fact = n => {
    if (n == 0)
        return 1;
    else
        return n * fact(n - 1); // コンパイルエラー: fact が見えない
};

コンパイルエラーメッセージ:

$ mcs test.cs
test.cs(9,28): error CS0165: Use of unassigned local variable `fact'
Compilation failed: 1 error(s), 0 warnings