title: Calculating prime numbers in Scala: how does this code work?
body: <p>So I've spent hours trying to work out exactly how this code produces prime numbers.</p>
  
  <pre><code>lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =&gt;
     ps.takeWhile{j =&gt; j * j &lt;= i}.forall{ k =&gt; i % k &gt; 0});
  </code></pre>
  
  <p>I've used a number of printlns etc, but nothings making it clearer.</p>
  
  <p>This is what I think the code does:</p>
  
  <pre><code>/**
   * [2,3] 
   * 
   * takeWhile 2*2 &lt;= 3 
   * takeWhile 2*2 &lt;= 4 found match
   *      (4 % [2,3] &gt; 1) return false.
   * takeWhile 2*2 &lt;= 5 found match
   *      (5 % [2,3] &gt; 1) return true 
   *          Add 5 to the list
   * takeWhile 2*2 &lt;= 6 found match
   *      (6 % [2,3,5] &gt; 1) return false
   * takeWhile 2*2 &lt;= 7
   *      (7 % [2,3,5] &gt; 1) return true
   *          Add 7 to the list
   */
  </code></pre>
  
  <p>But If I change <code>j*j</code> in the list to be 2*2 which I <em>assumed</em> would work exactly the same, it causes a stackoverflow error.</p>
  
  <p>I'm obviously missing something fundamental here, and could really use someone explaining this to me like I was a five year old.</p>
  
  <p>Any help would be greatly appreciated.</p>