title: How to avoid stack overflow in Haskell?
body: <p>Haskell does not support cycling for computation, instead it offers to use recursion algorithms. But this approach leads to growing of stack, and even stack overflow. I believe there should be approach to solve this problem in general. Here is the sample. I wanted to know, how many times <em>getClockTime</em> may be called per 5 seconds:</p>
  
  <pre><code>import System.Time
  
  nSeconds = 5
  
  main = do
      initTime &lt;- totalPicoSeconds `fmap` getClockTime
      doWork initTime 1
      where
      doWork initTime n = do
          currTime &lt;- totalPicoSeconds `fmap` getClockTime
          if (currTime - initTime) `div` 10 ^ 12 &gt;= nSeconds
              then print n
              else doWork initTime (n+1)
  
  totalPicoSeconds :: ClockTime -&gt; Integer
  totalPicoSeconds (TOD a b) = a * 10 ^ 12 + b
  </code></pre>
  
  <p>The program goes 5 seconds, but eventually I'm getting:</p>
  
  <blockquote>
    <p>Stack space overflow: current size 8388608 bytes.<br/>
    Use `+RTS -Ksize -RTS' to increase it.</p>
  </blockquote>
  
  <p>Manual management of stack size may help in particular case, but if I would wish to run this algo for 10 seconds, it may overflow again. So this is not a solution. How can I get this code working?</p>