尾递归

目录

通过阶乘计算来认识尾递归。阶乘可以用下面的表达式来描述:

n!=n*(n-1)*(n-2)…3*2*1

根据上面的表达式我们可以概括出下面的算法来计算阶乘:

n!=n*(n-1)!

1
2
3
4
5
6
7
8
9
10
11
public int Factorial(int number)
{
    if (number == 1)
    {
        return 1;
    }
 
    var temp = number * Factorial(number - 1);
 
    return temp;
}

函数调用:

1
2
var calculator=new Calculator();
var number = calculator.Factorial(6);

下面的替换模型描述了计算机是如何执行这一代码的:

当我们使用一个过大的数值,例如求:Factorial(5000)将会发生StackOverFlowException。

为了将它转化为一个尾递归函数,可以使用一种提供“累加器参数”的技术,我们需要向函数中添加一些参数,用来提供当前结果。

提供product参数,product=product*currentCount

提供currentCount参数,currentCount=currentCount+1

下面的代码描述了改造后的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int Factorial(int number)
{
    return TailedFactorial(1,1, number);
}
 
public int TailedFactorial(int product, int currentNumber, int number)
{
    if (currentNumber > number)
    {
        return product;
    }
 
    var temp = TailedFactorial(product*currentNumber, ++currentNumber, number);
 
    return temp;
}

与前面一样,我们看看这段代码的替换模型:

考虑第一个计算过程,这一过程展示了一个先逐步展开而后收缩 的形状,在展开阶段描述了计算机在每次调用时如何向堆栈中添加一个堆栈帧的,收缩阶段则表现为这些运算的实际执行。要执行这种计算过程,计算机就需要维护好那些以后将要执行的操作轨迹。

与之对应,第二个计算过程并没有任何增长或收缩。对于任何一个n,在计算过程中的每一步,所有的东西都保存在变量product,currentNumber和number中,在这种场景下,在计算过程中的任何一点,这几个变量都提供了有关计算状态的一个完整描述。如果我们令上述计算在某两个步骤之间停下来,要想重新唤醒这一计算,只需要提供这三个变量即可。我们称这样的特性为尾递归。

递归在函数式编程中是绝对重要的,在尾递归技术的支持下,即使在极深度的递归调用中,也可以避免堆栈溢出。

在函数式语言中还存在一种极其重要的数据结构:“列表”。关于函数式列表的一个重要事实就是它们是不可变的,也就意味着我们可以构造一个列表,但不能取得一个已有列表并修改它;也不能添加或删除一个元素。这一数据结构极其适合通过递归的方式来处理,以F#为例,针对一个列表编写map和filter函数:

通过模式匹配处理列表的两个分支:

1
2
3
4
5
let rec mapN f list=
    match list with
    | [] ->[]
    | x::xs-> let xs=(mapN f xs)
                f(x)::xs
1
2
3
4
5
let rec filterN f list=
    match list with
    | []->[]
    | x::xs->let xs=(filterN f xs)
               if f(x) then x::xs else xs

当我们处理一个大型列表的时候,这两个函数将会发生StackOverflowException.

1
2
let large=[1..100000]
large|>mapN (fun n->n*n)

解决这一问题的办法是采用尾递归:

1
2
3
4
5
6
7
let map f list=
    let rec map' f list tempList=
        match list with
        |[]->List.rev(tempList)
        |x::xs->let tempList=f(x)::tempList
                map' f xs tempList
    map' f list []

在map函数内部添加一个累加器参数tempList,我们在对列表进行迭代时收集元素并将它们存储在累加器内,一旦到达了结尾部分,就可以返回我们已经收集的元素了。

filter函数的尾递归实现:

1
2
3
4
5
6
7
let filter f list=
    let rec filter' f list tempList=
        match list with
        |[]->List.rev(tempList)
        |x::xs->let tempList=if f(x) then x::tempList else tempList
                filter' f xs tempList
    filter' f list []

 

参考书籍:SICP

                       Real world Functional Programming with examples in F# and c#

posted @   richiezhang  阅读(1634)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示