简体   繁体   English

C#:使用 Lambda 的递归函数

[英]C#: Recursive functions with Lambdas

The below does not compile:以下不编译:

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

Local variable 'fac' might not be initialized before accessing局部变量“fac”在访问之前可能未初始化

How can you make a recursive function with lambdas?你怎么能用 lambdas 做一个递归函数?

[Update] [更新]

Here are also two links that I found interesting to read:这里还有两个我觉得有趣的链接:

  1. Eric Lippert's "Why does a recursive lambda cause a definite assignment error?" Eric Lippert 的“为什么递归 lambda 会导致明确的赋值错误?”
  2. Anonymous Recursion in C# C#中的匿名递归

This particular style of function is not supported by C# as a single line declaration. C# 不支持这种特殊风格的函数作为单行声明。 You have to separate out the declaration and definition into 2 lines您必须将声明和定义分成两行

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

Well geez, if you'd just typed "why does a recursive lambda cause a definite assignment error?" 那么geez,如果你只是输入“为什么递归lambda导致明确的赋值错误?” into some search engine, you'd have found the answer in my article on the subject. 在一些搜索引擎中,你已经在我关于这个主题的文章中找到了答案。

:-) :-)

http://blogs.msdn.com/ericlippert/archive/2006/08/18/why-does-a-recursive-lambda-cause-a-definite-assignment-error.aspx http://blogs.msdn.com/ericlippert/archive/2006/08/18/why-does-a-recursive-lambda-cause-a-definite-assignment-error.aspx

You'll have to create fac first und assign it later (which is pretty unfunctional because it depends on multiple assignment) or use so called Y-combinators .您必须先创建fac并稍后分配它(这非常不起作用,因为它依赖于多个分配)或使用所谓Y-combinators

Example:例子:

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));            
}

But note that this might be somewhat hard to read/understand.但请注意,这可能有点难以阅读/理解。

从 C# 7.0 开始,您终于可以通过使用本地函数而不是 lambda 来做类似的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM