Note that there are some explanatory texts on larger screens.

plurals
  1. POHaskell recursive list comprehension causes C Stack Overflow
    text
    copied!<p>So I'm making a list of prime numbers to help me learn haskell using simple trial division (no fancy stuff until I get better with the language). I'm trying to use the following code:</p> <pre><code>primes = 2 : [ x | x &lt;- [3..], all (\p -&gt; (mod x p) /= 0) primes] </code></pre> <p>This is loaded without an error. However:</p> <pre><code>&gt;take 2 primes [2ERROR - C stack overflow </code></pre> <p>I tried the same thing with nested list comprehensions. It doesn't work. I would guess that I'm making too many recursive calls, but this shouldn't be the case if i'm only computing one prime. In my mind the lazy evaluation should make it so that <code>take 2 primes</code> does something along the lines of:</p> <pre><code>primes = 2 : [ 3 | all (\p -&gt; (mod 3 p) /= 0) [2] ] </code></pre> <p>Which doesn't require all that much computation - <code>mod 3 2 == True</code>, so <code>all (\p -&gt; (mod 3 p) /= 0) == True</code>, which means <code>take 2 primes == [2, 3]</code>, right? I don't understand why this isn't working. Hopefully someone much more versed in the black magic of functional programming can help me...</p> <p>This is on HUGS, if that makes any difference.</p> <p>EDIT- I was able to come up with this solution (not pretty):</p> <pre><code>primes = 2 : [ x | x &lt;- [3..], all (\p -&gt; (mod x p) /= 0) (takeWhile (&lt;= (ceiling (sqrt (fromIntegral x)))) primes)] </code></pre> <p>EDIT2- The program works fine when interpreted through HUGS or GHCi, but when I try to compile it with GHC, it outputs <code>test: &lt;&lt;loop&gt;&gt;</code>. Anybody know what the problem is?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload