title: Haskell - efficient equivalent of for loop?
body: <p>I've been doing some experiments and here's something I found. Consider the following C program:</p>
  
  <pre><code>int main()
  {
     for(int i = 0;
         i &lt; 1000000;
         ++i)
     {}
  }
  </code></pre>
  
  <p>and the following Haskell program:</p>
  
  <pre><code>import System.IO
  
  loop :: Int -&gt; IO ()
  loop n = if 0 == n then return () else loop (n-1)
  
  main = loop 1000000
  </code></pre>
  
  <p>Here is the output of <code>time</code> for the above C program:</p>
  
  <pre><code>real    0m0.003s
  user    0m0.000s
  sys 0m0.000s
  </code></pre>
  
  <p>...and for the Haskell program:</p>
  
  <pre><code>real    0m0.028s
  user    0m0.027s
  sys 0m0.000s
  </code></pre>
  
  <p>At first I thought that gcc detected an empty loop and optimized it out, but after increasing the number of iterations, the running time of the program also increased. Here are the outputs of <code>time</code> for both of the programs, with the number of iterations set to 10000000:</p>
  
  <p>C version</p>
  
  <pre><code>real    0m0.024s
  user    0m0.023s
  sys 0m0.000s
  </code></pre>
  
  <p>Haskell version</p>
  
  <pre><code>real    0m0.245s
  user    0m0.247s
  sys 0m0.000s
  </code></pre>
  
  <p>As you can see, the Haskell program is 10 times slower.</p>
  
  <p>Question is: what is the efficient alternative to the <code>for</code> loop in Haskell? As we just saw, simple recursion slows the program down about 10 times (and this is probably with the tail recursion optimizations done). </p>