title: How does haskell manage memory of recursive function calls
body: <p>I have been working on a problem that benefits a lot from catching results of my functions and in my research I came across <a href="https://wiki.haskell.org/Memoization" rel="nofollow noreferrer">this</a> article. I am stunned at how simple is the core in "Memoization with recursion" section namely:</p>
  
  <pre><code>memoized_fib :: Int -&gt; Integer
  memoized_fib = (map fib [0 ..] !!)
     where fib 0 = 0
           fib 1 = 1
           fib n = memoized_fib (n-2) + memoized_fib (n-1)
  </code></pre>
  
  <p>I feel like I understand <strong>how</strong> it work but do correct me if I'm wrong - this function saves a list which is populated using same function. </p>
  
  <p>What bothers me is that I don't understand <strong>why</strong> this works, originally I was under impression that once haskell evaluates a function it releases memory that was used to store variables inside this function, but here it seems that if part of the list was evaluated by one call of this function those values are still available to another call of the same function. </p>
  
  <p>Just typing this up makes my head hurt, because I don't understand why value used in calculation of <code>fib 2</code> should be available in calculation of <code>fib 3</code> or better yest <code>fib 100</code>?</p>
  
  <p>My gut feeling tells me that this behavior has two problems(I'm probably wrong but again not sure why):</p>
  
  <ul>
  <li>purity of this function we are evaluating one call using variable that did not arrive from parameters of this function</li>
  <li>memory leaks no longer sure when will haskell release memory from this list</li>
  </ul>