title: How to evaluate a lazy list once?
body: <p><a href="http://www.garrisonjensen.com/2015/05/13/haskell-programs-are-lies.html" rel="nofollow noreferrer">I referred to this post</a> to compute a function <code>nthPrimes</code> that takes 
  a list of n and returns a list of nth prime:</p>
  
  <pre><code>import qualified Data.Set as PQ
  
  main :: IO ()
  main = print $ nthPrimes ns
    where
      ns = [1,3,10]
  
  nthPrimes :: [Int] -&gt; [Integer]
  nthPrimes = map (primes !!)
  
  primes :: [Integer]
  primes = 2:sieve [3,5..]
    where
      sieve (x:xs) = x : sieve' xs (insertprime x xs PQ.empty)
  
      sieve' (x:xs) table
          | nextComposite == x = sieve' xs (adjust x table)
          | otherwise          = x : sieve' xs (insertprime x xs table)
        where
          (nextComposite,_) = PQ.findMin table
  
      adjust x table
          | n == x    = adjust x (PQ.insert (n', ns) newPQ)
          | otherwise = table
        where
          Just ((n, n':ns), newPQ) = PQ.minView table
  
      insertprime p xs = PQ.insert (p*p, map (*p) xs)
  </code></pre>
  
  <p>So, this will print <code>[3,7,31]</code>.</p>
  
  <p>However, since the <code>primes</code> function is lazy, it will be evaluated again and again in each call to get an nth-prime, but actually, we could just evaluate all the primes once if we know the <code>n</code> has a Max limit, (for instance <code>1000</code>), because <code>primes</code> never changes, and computing <code>primes</code> is CPU and Memory heavy. </p>
  
  <p>So the question is how to force the evaluation of <code>primes</code> for the first X elements so that all the pre-evaluated elements can be reused in functions that take from it? </p>
  
  <p>I believe reusing the pre-evaluated elements will reduce the overall Memory usage, especially when <code>ns</code> is a long list, correct?</p>