[Haskell-beginners] Simple laplace solver

Edward Z. Yang ezyang at MIT.EDU
Thu Mar 26 23:57:19 EDT 2009


Hello all,

As my first foray into the wonderful world of Haskell programming, I
wrote a simple program that solves Laplace equations. The program is 44
lines, and I would greatly appreciate comments on how I could make it
better, with regards to Haskell idioms, performance and readability.

Cheers,
Edward

import Data.Array

data Node = Node {
     isBoundary :: Bool,
     value :: Double
}

instance Show Node where
     show (Node True value)  = show value ++ "*"
     show (Node False value) = show value

blankArray :: Ix i => (i, i) -> a -> Array i a
blankArray (a, b) x = array (a, b) [(i, x) | i <- range (a, b)]

fillBox :: Ix i => (i, i) -> a -> Array i a -> Array i a
fillBox (a, b) value m = m // [(i, value) | i <- range(a, b)]

average :: Fractional a => [a] -> a
average list = sum list / fromIntegral (length list)

solve :: Array (Integer, Integer) Node -> Array (Integer, Integer) Node
solve m =
     if maximum deltas > 0.0001
         then solve n
         else n
     where
         n = array (min, max) [(i, solveNode i) | i <- range(min, max)]
         deltas = map delta $ zip (values m) (values n)
         delta (x, y) = abs (x - y)
         values a = map value $ elems a
         (min, max) = bounds m
         solveNode (a, b) =
             if isBoundary $ node
                 then node
                 else averageNode
             where
                 node = m ! (a, b)
                 averageNode = Node False $
                     average [value $ m ! i | i <- [(a+1,b),(a-1,b),(a,b+1),(a,b-1)]]

myArray =
       fillBox    ((3,3), (5,5)) (Node True 100)
     $ fillBox    ((1,1), (8,8)) (Node False 0)
     $ blankArray ((0,0), (9,9)) (Node True 0)



More information about the Beginners mailing list