函数式编程中的无限循环? [英] infinite loop in functional programming?

查看:325
本文介绍了函数式编程中的无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




示例:当使用函数式编程时,可以使用无限循环windows API来获取windows消息,通常在一个循环中实现。



我知道有可能创建一个函数,使其无限期地继续进行递归。我预计这会导致堆栈溢出。




  • 无限循环错误的函数式编程思维?

  • 是操作系统的界面还是硬件的问题?




它在我看来不像功能程序/ os可以继续自行运行

我有一些编写功能程序的经验,但这一直困扰着我。
请分享您关于这些问题的想法/见解

正如其他人发布的,无限循环 可以通过尾递归



例如因为编译器可以优化 loop 的尾递归调用,所以 loop()将作为无限循环(在常量堆栈空间中)

  let loop()= do {
println(foo)
loop()
}

但是


是函数式编程中错误思维的无限循环吗?有一点。考虑你的Windows API的例子与无限循环。这不过是功能性的。请记住 - 功能意味着考虑(和它们的含义)。因此,人们宁愿选择一种基于反应/事件的方法[伪函数代码]

 (onClick form1)
|> Event.subscribe(\pt-> do {print $我点击了++(show pt)})

所以


它在我看来不像功能程序/ os可以继续运行

在技术上是错误的 - 您可以 实现无限循环 - 但这样做通常没有(功能)点。除了某种IO轮询之外,为什么还需要这个?以纯粹功能性的方式转换值应该终止是有意义的。


  • I was wondering: can infinite loops be done in functional programming?

example: when using the windows API to get windows messages, it is usually implemented in a loop.

I know it is possible to make a function that will keep going into recursion indefinitely. I expect that this will result in a stack overflow.

  • are infinite loop the wrong mind-set for functional programming ?

  • is the interface of the operating system or the hardware the problem ?

it doesn't seem to me like a functional program/o.s. could keep running by itself

I have a tiny bit of experience writing functional programs but this has always bothered me. please share your thoughts/insights about these issues

解决方案

As others have posted, an infinite loop is possible through tail recursions.

E.g. loop() will effectively run as an infinite loop (in constant stack space) since the compiler can optimize out the tail-recursive call of loop at the end.

let loop() = do {
  println("foo")
  loop()
}

But

are infinite loop the wrong mind-set for functional programming ?

still got a point. Consider your Windows-API example with the infinite loop. That's anything but functional. Remember - functional means thinking in values (and what they mean). Therefore, one would rather go a reactive/event-based approach like that [Pseudo-functional code]

  (onClick form1)
|> Event.subscribe (\pt-> do { print $ "I was clicked at " ++ (show pt) })

So

it doesn't seem to me like a functional program/o.s. could keep running by itself

is technically wrong - you can implement infinite loops - but there is often no (functional) point in doing so. Why should one need that except for some kind of IO polling? Transforming values in a purely functional way should terminate to be meaningful.

这篇关于函数式编程中的无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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