不動点関数
Y(M) = M(Y(M)) となる関数 Y の事を不動点関数という。
C#だとこんな感じ。
class Fix<T> { protected delegate T FuncType(T arg); protected delegate FuncType FixType(FuncType func); protected static FuncType Y(FixType maker) { FuncType f = null; f = delegate(T arg) { return f(arg); }; f = maker(f); return f; } }
で、以下のように使う。
class Program : Fix<int> { static FuncType M(FuncType fact) { return delegate(int n) { return n == 0 ? 1 : n * fact(n - 1); }; } static void Main(string[] args) { for (int n = 0; n <= 10; ++n) Console.WriteLine(Y(M)(n)); } }
変数を使わずに再帰関数を定義するのに使える。
つまり・・・
class Program : Fix<int> { static void Main(string[] args) { // A for (int i = 0; i <= 10; ++i) Console.WriteLine(Y( delegate(FuncType fact) { return delegate(int n) { return n == 0 ? 1 : n * fact(n - 1); }; })(i)); // B FuncType f = null; // null代入は警告防止 f = delegate(int n) { return n == 0 ? 1 : n * f(n - 1); }; for (int i = 0; i <= 10; ++i) Console.WriteLine(f(i)); } }
Bでは関数名fが必要だが、Aでは必要がなくなっている。