WEB开发网
开发学院WEB开发ASP.NET lambda与递归 阅读

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

Tags:lambda 递归

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接