[Haskell-beginners] numerical integration over lists

Thomas Engel thomas.engel1 at gmx.net
Sun Feb 5 18:18:54 CET 2012


Hello Daniel,

thank you very much for pointing out a solution.  
> If I understand correctly, use
> 
> zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
> 
> -- calculates the list of differences between successive elements,
> -- differences [x1,x2,x3,...] = [x2-x1, x3-x2, ...]
> --
> -- We use subtract and don't swap the list arguments to zipWith
> -- becuase this way there is no need to handle an empty list
> -- specially, zipWith's definition lets (tail xs) unevaluated in that case.
> --
> differences :: Num a => [a] -> [a]
> differences xs = zipWith subtract xs (tail xs)
> 
> areas :: Floating a => [a] -> [a] -> [a]
> areas xs ys
>     = zipWith (\dx dy -> dx * dy/2) (differences xs) (differences ys)
> 
> -- if it should have been (y+y2)/2 above, make that
Yes, you are right. That should be an sum instead of a difference.

> -- sums ys, where sums ks = zipWith (+) ks
> -- or areas xs ys = zipWith (*) (differenses xs) (means ys)
> -- where means zs = map (/ 2) (sums zs)

I have changed the functions according your advice. But still I get an error:

differences :: Num a => [a] -> [a]
differences xs = zipWith subtract xs (tail xs)

areas :: Floating a => [a] -> [a] -> [a]
areas xs ys
    = zipWith (*) (differences xs) (means ys)
      where means zs = map (/ 2) (sums zs)
                       where sums ks = zipWith (+) ks

integrals xs ys = scanl (+) 0 (areas xs ys)

Couldn't match expected type `[b0]' with actual type `[c0] -> [c0]'
In the return type of a call of `sums'
In the second argument of `map', namely `(sums zs)'
In the expression: map (/ 2) (sums zs)

Thomas




More information about the Beginners mailing list