F#中的While或Tail Recursion,什么时候用? [英] While or Tail Recursion in F#, what to use when?

查看:32
本文介绍了F#中的While或Tail Recursion,什么时候用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,仅在 F# 中,这就是我现在的理解:

Ok, only just in F# and this is how I understand it now :

  • 有些问题本质上是递归的(构建或读出树结构仅举一个例子),然后您使用递归.在这些情况下,您最好使用尾递归来让堆栈中断

  • Some problems are recursive in nature (building or reading out a treestructure to name just one) and then you use recursion. In these cases you preferably use tail-recursion to give the stack a break

有些语言是纯函数式的,所以你必须使用递归而不是while循环,即使问题本质上不是递归的

Some languagues are pure functional, so you have to use recursion in stead of while-loops, even if the problem is not recursive in nature

所以我的问题是:由于 F# 也支持命令式范式,您会在 F# 中使用尾递归来解决不是自然递归问题的问题吗?特别是因为我已经阅读了编译器识别尾递归并且无论如何只是在 while 循环中转换它?

So my question : since F# also support the imperative paradigm, would you use tail recursion in F# for problems that aren't naturally recursive ones? Especially since I have read the compiler recongnizes tail recursion and just transforms it in a while loop anyway?

如果是这样:为什么?

推荐答案

最佳答案是都不是".:)

The best answer is 'neither'. :)

while 循环和尾递归都有一些丑陋之处.

There's some ugliness associated with both while loops and tail recursion.

虽然循环需要可变性和效果,虽然我不反对适度使用这些,尤其是当封装在局部函数的上下文中时,当您开始引入效果时,有时确实会觉得您的程序混乱/丑陋只是为了循环.

While loops require mutability and effects, and though I have nothing against using these in moderation, especially when encapsulated in the context of a local function, you do sometimes feel like you're cluttering/uglifying your program when you start introducing effects merely to loop.

尾递归通常具有需要额外累加器参数或继续传递样式的缺点.这会用额外的样板来干扰程序以调整函数的启动条件.​​

Tail recursion often has the disadvantage of requiring an extra accumulator parameter or continuation-passing style. This clutters the program with extra boilerplate to massage the startup conditions of the function.

最好的答案是既不使用while循环也不使用递归.高阶函数和 lambda 是你的救星,尤其是映射和折叠.如果您可以将这些控制结构封装在可重用的库中,然后简单地声明性地陈述计算的本质,为什么还要为循环使用凌乱的控制结构?

The best answer is to use neither while loops nor recursion. Higher-order functions and lambdas are your saviors here, especially maps and folds. Why fool around with messy control structures for looping when you can encapsulate those in reusable libraries and then just state the essence of your computation simply and declaratively?

如果您养成经常调用 map/fold 而不是使用循环/递归的习惯,并且提供 fold 函数以及您引入的任何新的树结构数据类型,那么您将走得更远.:)

If you get in the habit of often calling map/fold rather than using loops/recursion, as well as providing a fold function along with any new tree-structured data type you introduce, you'll go far. :)

对于那些有兴趣了解有关 F# 折叠的更多信息的人,何不查看我的 第一 博客 关于该主题的系列帖子?

For those interested in learning more about folds in F#, why not check out my first three blog posts in a series on the topic?

这篇关于F#中的While或Tail Recursion,什么时候用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆