[Haskell-cafe] Area from [(x,y)] using foldl

michael rice nowgate at yahoo.com
Sun Nov 8 16:30:18 EST 2009

That's certainly better than mine, but I'm lost again, with the following. What seemed like a simple improvement doesn't compile.



This works.

area :: [(Double,Double)] -> Double
area ps = abs $ (/2) $ area' (last ps) ps
            where area' _ [] = 0
                  area' (x0,y0) ((x,y):ps) = (x0-x)*(y0+y) + area' (x,y) ps

*Main> let p = [(0.0,0.0),(1.0,0.0),(1.0,1.0),(0.0,1.0),(0.0,0.0)]
*Main> area (last p) p


This doesn't.

area :: [(Double,Double)] -> Double
area p = abs $ (/2) $ area' (last p):p
         where area' [] = 0
               area' ((x0,y0),(x,y):ps) = ((x0-x)*(y0+y)) + area' (x,y):ps   

--- On Sun, 11/8/09, Chaddaï Fouché <chaddai.fouche at gmail.com> wrote:

From: Chaddaï Fouché <chaddai.fouche at gmail.com>
Subject: Re: [Haskell-cafe] Area from [(x,y)] using foldl
To: "michael rice" <nowgate at yahoo.com>
Cc: "Eugene Kirpichov" <ekirpichov at gmail.com>, haskell-cafe at haskell.org
Date: Sunday, November 8, 2009, 3:52 PM

On Sun, Nov 8, 2009 at 9:04 PM, michael rice <nowgate at yahoo.com> wrote:

Of course! Back to the drawing board.

If I understand the problem correctly, I'm not convinced that foldl is the right approach (nevermind that foldl is almost never what you want, foldl' and foldr being the correct choice almost always). My proposition would be the following :

> area ps = abs . (/2) . sum $ zipWith (\(x,y) (x',y') -> (x - x') * (y + y')) ps (tail $ cycle ps)

I think it express the algorithm more clearly.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091108/f0671c3c/attachment.html

More information about the Haskell-Cafe mailing list