C#でProject Euler(2) ラムダ式

次のコードを見てください。

using System;

class lambda_test {
    static void Main(string[] args) {
        Func<int,int>   f = (x) => x + 1;   // ラムダ式
        
        Console.WriteLine(f(1));    // 2
    }
}

このfの定義がラムダ式です。型はFuncとなっています。引数がint一つで返り値がintという意味です。引数の型を明示することもできます。

        Func<int,int>   f = (int x) => x + 1;

引数が複数なら、例えば次のようになります。

        Func<int,int,double>    mean = (x, y) => (x + y) / 2.0;
        
        Console.WriteLine(mean(1, 2));      // 1.5

再帰もできますよ。

        Func<int,int>   factorial = null;
        factorial = (x) => x == 0 ? 1 : x * factorial(x - 1);
        
        Console.WriteLine(factorial(7));    // 5040

関数の引数にするときは、型推論が効くので型を明示しなくてもよいです。

    static int g(Func<int,int> f, int x) {
        return f(x);
    }
    
    static void Main(string[] args) {
        Console.WriteLine(g((x) => x + 2, 3));      // 5
    }

面白くない例ですが、次回にちゃんとした使い方が示されます。