recursion - 为什么此 F# 代码不是尾递归的?

标签 recursion f# tail-recursion

我正在查看 Visual Studio 2015 提供的 F#“教程”模板中的代码,我看到了这段代码;我想知道为什么第一个函数不是尾递归的;我想我明白了,但想确认一下:

/// Computes the sum of a list of integers using recursion.
let rec sumList xs =
    match xs with
    | []    -> 0
    | y::ys -> y + sumList ys

/// Make the function tail recursive, using a helper function with a result accumulator
let rec private sumListTailRecHelper accumulator xs =
    match xs with
    | []    -> accumulator
    | y::ys -> sumListTailRecHelper (accumulator+y) ys

第一个不是尾递归的,因为“+”是一个函数并且它的两个参数首先被评估?因此,实际的求值顺序是:y,然后 sumList ys,然后 +?而在第二种情况下,求值的顺序是:accumulator,y,+ 然后 sumListTailRecHelper(..)?

最佳答案

如果递归调用返回后没有什么可做的,则调用是尾递归的。因此,最后一次调用相当于返回到函数代码的开头,并修改了参数。

在第一个函数中,您仍然需要将 y 添加到结果中。

关于recursion - 为什么此 F# 代码不是尾递归的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809475/

相关文章:

c++ - 如果结构作为递归函数中的参数传递,我如何初始化结构的成员变量?

sql - 从 SQL 递归查询中添加额外的列

python - 在 Python 中迭代 N 个维度

java - boolean 递归

c# - C# 中的 F# 中缀运算符?

python - 如何将以下函数变成尾递归函数?

f# - 向 F# 可区分联合添加常量字段

powershell - 为什么从 PowerShell 调用 F# 代码时收到 MissingMethodException?

algorithm - 证明两个算法相同

f# - 将此 F# 代码重构为尾递归