C#: 使用Lambda的递归函数

29

3
你真的想要这样做吗?看起来这会让代码难以维护和理解。 - Ian
3个回答

50

在C#中,不支持这种单行声明的函数风格。你需要将声明和定义分成两行。

Func<int, int> fac = null;
fac = n => (n <= 1) ? 1 : n * fac(n - 1);

12

首先需要创建fac,然后再进行分配(这种方法不太实用,因为它依赖于多次分配),或者使用所谓的Y-combinators

示例:

delegate Func<TIn, TOut> FixedPointFunction<TIn, TOut>(Func<TIn, TOut> f);

static Func<T, TRes> Fix<T, TRes>(FixedPointFunction<T, TRes> f) {
    return f(x => Fix(f)(x));
}

static void Main(string[] args) {

    var fact = Fix<int, int>(f => x => (x <= 1) ? x : x * f(x - 1));

    Console.WriteLine(fact(5));            
}

但请注意,这可能有些难以阅读/理解。

-1

自从C# 7.0以来,你终于可以使用本地函数代替lambda来做类似的事情。

int fac(int n) => (n <= 1) ? 1 : n * fac(n - 1);

本地函数不是Lambda表达式:https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/local-functions#local-functions-vs-lambda-expressions - Lord of the Goo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接