[Haskell-beginners] doing state right

Chaddaï Fouché chaddai.fouche at gmail.com
Thu Apr 23 04:03:50 EDT 2009


On Thu, Apr 23, 2009 at 7:59 AM, Floptical Logic
<flopticalogic at gmail.com> wrote:
> I am using a PPM library to generate a square image where each white
> pixel represents a prime number.  The PPM library takes a function
> (Int -> Int -> Colour) to create the image.  This interface isn't
> ideal but it is what I have to work with.  I am convinced that using a
> sieve is faster than testing every pixel in the image for primality,
> but the (Int -> Int -> Colour) interface makes this awkward.

Only because you're still not familiar with arrays in Haskell, this
interface is absolutely not a problem :

main = quick_ppm "foo.ppm" (\i j -> isPrime ((i-1)*limit+j)) limit limit
  where
    isPrime n = primeSieve ! n
    primeSieve :: UArray Int Bool
    primeSieve = accumArray (\_ _ -> True) False (0,limit*limit) $ zip
primes (repeat ())

There are in fact algorithms that would directly do the sieve on an
array (the classical algorithm would do nicely) but if you don't need
exceedingly good performance, that will do.

-- 
Jedaï


More information about the Beginners mailing list