虽然在F#或尾递归,什么时候使用? [英] While or Tail Recursion in F#, what to use when?

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

问题描述




  • 有些问题本质上是递归的(建立或读出树状结构来命名一个),然后使用递归。在这些情况下,你最好使用尾递归来给栈一个中断。


  • 有些语言是纯功能的,所以你必须用递归来代替while-即使问题本质上不是递归的




所以我的问题是:既然F#也支持命令范式,你会使用F#中的尾递归来处理那些不是自然递归的问题吗?特别是因为我已经阅读了编译器recongnizes尾递归,只是转换它在一个while循环吗?

如果是这样:为什么?

解决方案

最好的答案是'既不'。 :)

while循环和尾递归都有一些丑陋。

while循环需要可变性和效果,尽管我没有什么反对在适度使用它们,特别是当封装在本地函数的上下文中时,您有时会觉得像你当你开始只是为了循环而引入效果时,你的程序会混乱/丑化你的程序。

尾递归常常有一个缺点,就是需要额外的累加器参数或延续传递样式。这会让程序变得杂乱无章,仿效该函数的启动条件。​​



最好的答案是既不使用while循环,也不使用递归。高阶函数和lambda是你的救星,特别是地图和褶皱。为什么要用混乱的控制结构进行循环,当你可以将它们封装在可重用的库中,然后简单地声明你的计算的本质?

如果你进入习惯经常调用map / fold,而不是使用循环/递归,以及提供折叠函数以及您所介绍的任何新的树形结构数据类型,您将走得更远。 :)

对于那些有兴趣了解更多关于F#中的折叠的人,为什么不查看我的 first 三个 博客中的帖子系列话题?

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

  • 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

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?

If so : why ?

解决方案

The best answer is 'neither'. :)

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.

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?

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. :)

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#或尾递归,什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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