递归地实现lambdas

递归地实现lambdas

本文介绍了递归地实现lambdas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何递归地实现lambas。

how to implement lambas recursively.

推荐答案

Func<int, int> Factorial = null;
Factorial = x => (x <= 0) ? 1 : x * Factorial(x - 1);
Func<int, int> incorrectFactorial = Factorial;
Factorial = x => x;

int ans = incorrectFactorial(5);



由于重新分配了标识符<$ c $,因此 ans 的值为20 c> Factorial 。

绑定递归方法的名称需要保护:


The value of ans here is 20 because of the reassignment of the identifier Factorial.
The name binding the recursive method needs to be protected:

Func<int, int> Factorial = null;
Factorial = x => {
  Func<int, int> internalFactorial = null;
  internalFactorial = xi => (xi <= 0) ? 1 : xi * internalFactorial(xi - 1);
  return internalFactorial(x);
};

Func<int, int> otherFactorial = Factorial;
Factorial = x => x;

int ans = otherFactorial(5);



这里 ans 的值是正确的120,因为递归标识符是范围内部的of lambda。

另一种方法是使用一个方法返回 Func< int,int>


Here the value of ans is the correct 120 because the recursion identifier was internal to the scope of the lambda.
Another way to accomplish this would be to have a method that returns a Func<int, int>:

static Func<int, int> GetFactorialFunction()
{
  Func<int, int> Factorial = null;
  Factorial = x => (x <= 0) ? 1 : x * Factorial(x - 1);
  return Factorial;
}



并调用返回的函数:


and invoke the returned function:

int ans = GetFactorialFunction()(5);



Of当然,此时使用lambda 可能是多余的,因为函数可以直接实现为命名的递归函数。


Of course, at this point using a lambda is probably superfluous since the function could be implemented directly as a named, recursive function.


Func<int, int> factorialValue = null;
factorialValue = x => (x == 0) ? 1 : x * factorialValue(x - 1);


这篇关于递归地实现lambdas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:31