Personal tools

User:WillNess

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
m
Line 6: Line 6:
primes = 2 : g (fix g) -- double staged production idea due to M. O'Neill
primes = 2 : g (fix g) -- double staged production idea due to M. O'Neill
where
where
-
g xs = 3 : (gaps 5 $ foldi (\(q:qs)-> (q:) . union qs)
+
g xs = 3 : (gaps 5 $ foldi (\(q:qs) -> (q:) . union qs)
[[p*p, p*p+2*p..] | p <- xs])
[[p*p, p*p+2*p..] | p <- xs])
 +
gaps k s@(x:xs)
 +
| k < x = k : gaps (k+2) s -- | k<=x = minus [k,k+2..] xs
 +
| True = gaps (k+2) xs -- inlined to avoid a space leak
-
fix g = xs where xs = g xs
+
fix g = xs where xs = g xs -- global defn to avoid space leak
-
 
+
-
gaps k s@(x:xs) = if k < x -- | k<=x = minus [k,k+2..] xs
+
-
then k : gaps (k+2) s -- inlined to avoid a space leak
+
-
else gaps (k+2) xs
+
</haskell>
</haskell>
<code>foldi</code> is on [[Fold#Tree-like_folds|Tree-like folds]]. More at [[Prime numbers#Sieve_of_Eratosthenes|Prime numbers]].
<code>foldi</code> is on [[Fold#Tree-like_folds|Tree-like folds]]. More at [[Prime numbers#Sieve_of_Eratosthenes|Prime numbers]].

Revision as of 13:38, 7 August 2011

I am a newbie, interested in Haskell.

I like this:

primes = 2 : g (fix g) -- double staged production idea due to M. O'Neill
  where
    g xs = 3 : (gaps 5 $ foldi (\(q:qs) -> (q:) . union qs)
                               [[p*p, p*p+2*p..] | p <- xs])
    gaps k s@(x:xs)                
       | k < x = k : gaps (k+2) s     -- | k<=x = minus [k,k+2..] xs
       | True  =     gaps (k+2) xs    -- inlined to avoid a space leak
 
fix g = xs where xs = g xs            -- global defn to avoid space leak

foldi is on Tree-like folds. More at Prime numbers.