C#: Recursive functions with Lambdas

不羁岁月 提交于 2019-11-26 17:38:33

问题


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

How can you make a recursive function with 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?"
  2. Anonymous Recursion in C#

回答1:


This particular style of function is not supported by C# as a single line declaration. 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);



回答2:


Well geez, if you'd just typed "why does a recursive lambda cause a definite assignment error?" 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




回答3:


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.

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.




回答4:


since c# 7.0 you finally can do this in one line using a local function

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


来源:https://stackoverflow.com/questions/1079164/c-recursive-functions-with-lambdas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!