Why should recursion be preferred over iteration?
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 ie recursion is available) ? Please shed some light on this. Thanks.
Iteration is more performant than recursion, right?
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.
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.
Try implementing depth-first search recursively and iteratively and tell me which one gave you an easier time of it. Or merge sort. For a lot of problems it comes down to explicitly maintaining your own stack vs. leaving your data on the function stack.
I can't speak to Haskell as I've never used it, but this is to address the more general part of the question posed in your title.
Haskell不允许迭代,因为迭代涉及可变状态(索引)。
链接地址: http://www.djcxy.com/p/86754.html下一篇: 为什么递归比迭代更受欢迎?