[Haskell-beginners] doing state right

Floptical Logic flopticalogic at gmail.com
Thu Apr 23 01:59:37 EDT 2009


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.  The code
below attempts to treat the list of prime numbers as a stack via
global mutable state, popping the head whenever the pixel is prime.
Obviously this is not idiomatic Haskell.  What is the correct approach
of dealing with state here?  Thanks for reading.

import ONeillPrimes
import PPM6
import Colour

import Data.IORef
import System.IO.Unsafe

limit = 2000
slimit = limit*limit

primeList = takeWhile (<=slimit) primes

p :: IORef [Int]
p = unsafePerformIO (newIORef primeList)

pcol n = unsafePerformIO $ do
    xs <- readIORef p
    if null xs then return black else
        if n == head xs
            then do
                writeIORef p (tail xs)
                return white
            else
                return black

main = quick_ppm "foo.ppm" (\i j -> pcol ((i-1)*limit+j)) limit limit

-- quick_ppm :: FilePath -> (Int -> Int -> Colour.Colour) -> Int -> Int -> IO ()


More information about the Beginners mailing list