问题描述
迭代比递归更高效,对吧?那么为什么有些人认为递归比迭代更好(用他们的话来说更优雅)?我真的不明白为什么像Haskell这样的语言不允许迭代并鼓励递归?鼓励表现不佳的东西并不是很荒谬(当更高性能的选项即递归可用时也是如此)?请详细说明一下。谢谢。
Iteration is more performant than recursion, right? Then why do some people opine that recursion is better (more elegant, in their words) than iteration? I really don't see why some languages like Haskell do not allow iteration and encourage recursion? Isn't that absurd to encourage something that has bad performance (and that too when more performant option i.e. recursion is available) ? Please shed some light on this. Thanks.
推荐答案
不一定。
这个概念来自许多类C语言,其中调用一个函数,递归或非递归,有很大的开销,并为每次调用创建一个新的堆栈帧。
Not necessarily.This conception comes from many C-like languages, where calling a function, recursive or not, had a large overhead and created a new stackframe for every call.
对于许多语言而言并非如此,递归与迭代版本相同或更高效。这些天,即使是一些C编译器也会将一些递归构造重写为迭代版本,或者重复使用堆栈帧进行尾递归调用。
For many languages this is not the case, and recursion is equally or more performant than an iterative version. These days, even some C compilers rewrite some recursive constructs to an iterative version, or reuse the stack frame for a tail recursive call.
这篇关于为什么递归优先于迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!