以下代码演示如何使用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