Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

infinite loop in functional programming?

  • 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

like image 661
symbiont Avatar asked Feb 04 '23 03:02

symbiont


1 Answers

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.

like image 152
Dario Avatar answered Feb 15 '23 18:02

Dario