c# - 函数式 C# 和尾递归

标签 c# functional-programming iterator

我有以下代码:

public static IEnumerable<T> cons<T>(T y, IEnumerable<T> xs)
{
    yield return y;
    foreach (var x in xs) yield return x;
}

public static bool empty<T>(IEnumerable<T> xs)
{
    return !xs.GetEnumerator().MoveNext();
}

public static T head<T>(IEnumerable<T> xs)
{
    Debug.Assert(!empty(xs), "Prelude.head: empty list");
    var e = xs.GetEnumerator(); e.MoveNext();
    return e.Current;
}

// repeat x is an infinite list, with x the value of every element
public static IEnumerable<T> repeat<T>(T x)
{
    return cons(x, repeat(x));
}

为什么 head(repeat(2)) 不起作用,但是如果我将 repeat 的实现替换为:

// repeat x is an infinite list, with x the value of every element
public static IEnumerable<T> repeat<T>(T x)
{
    for(;;) yield return x;
}

有用吗?

最佳答案

您的第一个实现不是尾递归。最后要执行的是 cons() 调用,但为了执行它,它必须评估 repeat(2)。为此,它必须(再次)评估 repeat(2)。以此类推,直到堆栈溢出。

您的第二个实现创建了一个枚举器,每次询问下一个元素时都会无限期地返回 x。没有重入,所以没有堆栈溢出。

关于c# - 函数式 C# 和尾递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6713455/

相关文章:

c++ - 使用指向存储在 vector 中的对象的指针... C++

C# - 创建 EnumRandomizer 类

c# - C#-在这种情况下无法使用list.Count()

c++ - 自动推断 bind1st(mem_fun(&my_class::f), this) 的类型?

python - 如何使用 Python/pandas 获取带有行摘要的分钟/小时财务数据?

Java:用迭代器删除所有对象

c# - 如何使用构造函数创建 C# 类并让它返回字符串?

c# - 部分类调试

java - 在 Java 中折叠顺序流

python - python中按成对标准对列表中的元素进行分组