b7j0c.org


a haskell solution for the fractal benchmark

time.hs is a naive (and potentially incorrect!) attempt to provide a haskell solution to the fractal benchmark recently listed on programming.reddit.com.

i compiled this and found it ran in just under three seconds, placing it more or less where i would expect compared to the other tools.

note - the code below has entities used in place of certain characters so that this page is valid xhtml. so don't cut and paste from it - use this link directly to the source

{-# OPTIONS -fexcess-precision -fvia-C -fbang-patterns -optc-O2 -optc-mfpmath=sse -optc-msse2 -optc-march=pentium4 #-}

module Main where
import System.Time

-- in the spirit of http://www.timestretch.com/FractalBenchmark.html

m :: Double -> Double -> Integer
m x y = f 0.0 0.0 (y - 0.5) x 0
    where f :: Double -> Double -> Double -> Double -> Integer -> Integer
          f zr zi cr ci i = 
              let bailout = 16
                  maxIterations = 1000
                  i' = i + 1
                  temp = zr * zi
                  zr2 = zr * zr
                  zi2 = zi * zi
                  zr' = zr2 - zi2 + cr
                  zi' = temp + temp + ci in
              case ((zi2 + zr2) > bailout) of
                   True -> i
                   False -> case (i > maxIterations) of
                              True -> 0
                              False -> f zr' zi' cr ci i'

main = do
  begin <- getClockTime
  let d = 40.0 :: Double
  let r = [(y,x) | y <- [-39..38], x <- [-39..38]] :: [(Double,Double)]
  let s = map (\p -> m ((snd p) / d) ((fst p) / d)) r
  print s
  end <- getClockTime
  let diff = diffClockTimes end begin
  print diff

last update 06/07/2007