Search code examples
loopsschemeracketstack-overflow

Will this endless loop code cause stack-overflow?


I want to run a program continuously till the user stops it using control-C or closes the window. Will following loop cause memory stack overflow or will it be tail-optimized recursion?

(define (f)
  (let loop ()
    (println "In loop.")
    (sleep 1)
    (loop)))

(f)

Also, is following also same or any different?

(for ((i (in-naturals)))
  (println "In for loop")
  (sleep 1))

Solution

  • Scheme standard has a requirement for tail call optimizations. The reason is that there are no other looping constructs in the language. You have do and such, but if you read the report they are syntactic sugar for a similar recursive procedure.

    Racket, as in #lang racket, share this with the standard schemes so that the first tail recursive code will never ever result in excess memory use or a stack overflow.

    The second is a #lang racket specific special form that still is syntactic sugar for a recursive procedure just like do is and it will not stack overflow either, however theoretically the number has the possibility to become larger than your systems available memory and get a out of memory error. Because of your one second delay this won't happen in this earths lifetime though so external factors like power outage or system hardware failure is more likely the end of your running recursive loop.