Personal tools

User:WillNess

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
Line 1: Line 1:
A perpetual Haskell newbie. I like ''[http://ideone.com/qpnqe this semi-one-liner]'':
+
A perpetual Haskell newbie. I like ''[http://ideone.com/qpnqe this one-liner]'':
  
 
<haskell>
 
<haskell>
--  inifinte folding idea due to Richard Bird
+
--  infinite folding idea due to Richard Bird
 
--  double staged production idea due to Melissa O'Neill
 
--  double staged production idea due to Melissa O'Neill
--  tree folding idea Dave Bayer / simplified formulation Will Ness
+
--  tree folding idea Dave Bayer / improved tree structure
primes = 2 : g (fix g)
+
--    Heinrich Apfelmus / simplified formulation Will Ness
  where               
+
primes = 2 : _Y ((3:) . gaps 5
    g xs = 3 : gaps 5 (foldi (\(c:cs) -> (c:) . union cs) []
+
                      . foldi (\(x:xs) -> (x:) . union xs) []
                            [[x*x, x*x+2*x..] | x <- xs])
+
                      . map (\p-> [p*p, p*p+2*p..]))  
  
fix g = xs where xs = g xs        -- global defn to avoid space leak
+
_Y g = g (_Y g)  -- multistage production
  
gaps k s@(c:t)                   -- == minus [k,k+2..] (c:t), k<=c,
+
gaps k s@(c:t)                       -- == minus [k,k+2..] (c:t), k<=c,
   | k < c = k : gaps (k+2) s    --    fused to avoid a space leak
+
   | k < c     = k : gaps (k+2) s    --    fused for better performance
   | True  =    gaps (k+2) t     
+
   | otherwise =    gaps (k+2) t    -- k==c
 
</haskell>
 
</haskell>
  

Revision as of 09:30, 6 August 2013

A perpetual Haskell newbie. I like this one-liner:

--   infinite folding idea due to Richard Bird
--   double staged production idea due to Melissa O'Neill
--   tree folding idea Dave Bayer / improved tree structure 
--     Heinrich Apfelmus / simplified formulation Will Ness
primes = 2 : _Y ((3:) . gaps 5  
                      . foldi (\(x:xs) -> (x:) . union xs) []
                      . map (\p-> [p*p, p*p+2*p..])) 
 
_Y g = g (_Y g)  -- multistage production
 
gaps k s@(c:t)                        -- == minus [k,k+2..] (c:t), k<=c,
   | k < c     = k : gaps (k+2) s     --     fused for better performance
   | otherwise =     gaps (k+2) t     -- k==c

foldi is on Tree-like folds page. union and more at Prime numbers.

The constructive definition of primes is the Sieve of Eratosthenes:

\textstyle\mathbb{S} = \mathbb{N}_{2} \setminus \bigcup_{p\in \mathbb{S}} \{p\,q:q \in \mathbb{N}_{p}\}

using standard definition

\textstyle\mathbb{N}_{k} = \{ n \in \mathbb{N} : n \geq k \}   . . . or,  \textstyle\mathbb{N}_{k} = \{k\} \bigcup \mathbb{N}_{k+1}   :) :) .

Trial division sieve is:

\textstyle\mathbb{T} = \{n \in \mathbb{N}_{2}: (\forall p \in \mathbb{T})(2\leq p\leq \sqrt{n}\, \Rightarrow \neg{(p \mid n)})\}

If you're put off by self-referentiality, just replace \mathbb{S} or \mathbb{T} on the right-hand side of equations with \mathbb{N}_{2}, but even ancient Greeks knew better.