lambda与递归
2012-07-23 08:46:13 来源:WEB开发网核心提示: 以下代码演示如何使用lambda来定义阶乘这一递归函数。C#Func<int, int> factorial = null;factorial = x => x == 0 ? 1 : x * factorial(x - 1);int f5 = factorial(5); // f5 == 120VB
以下代码演示如何使用lambda来定义阶乘这一递归函数。
C#
Func<int, int> factorial = null; factorial = x => x == 0 ? 1 : x * factorial(x - 1); int f5 = factorial(5); // f5 == 120
VB
Dim factorial As Func(Of Integer, Integer) factorial = Function(x) If(x = 0, 1, x * factorial(x - 1)) Dim f5 As Integer = factorial(5) ' f5 = 120
C++
#include <functional> function<int(int)> factorial = [&](int x){ return x == 0 ? 1 : x * factorial(x - 1); }; int f5 = factorial(5); // f5 == 120
赞助商链接