编程技巧:lambda与递归

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

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/zwvista/article/details/7773825
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞