I see what one problem is, what happens when I end up with (x,y):[]? However, I'm confused about how Haskell is "expecting" and "inferring" upon compilation.
Michael
--- On Sun, 11/8/09, michael rice <nowgate@yahoo.com> wrote:
From: michael rice <nowgate@yahoo.com> Subject: Re: [Haskell-cafe] Area from [(x,y)] using foldl To: "Chaddaï Fouché" <chaddai.fouche@gmail.com> Cc: haskell-cafe@haskell.org Date: Sunday, November 8, 2009, 4:30 PM
That's certainly better than mine, but I'm lost again, with the following. What seemed like a simple improvement doesn't compile.
Michael
===============
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 1.0 *Main>
===============
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@gmail.com> wrote:
From: Chaddaï Fouché <chaddai.fouche@gmail.com> Subject: Re: [Haskell-cafe] Area from [(x,y)] using foldl To: "michael rice" <nowgate@yahoo.com> Cc: "Eugene Kirpichov" <ekirpichov@gmail.com>, haskell-cafe@haskell.org Date: Sunday, November 8, 2009, 3:52 PM
On Sun, Nov 8, 2009 at 9:04 PM, michael
rice <nowgate@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. -- Jedaï
|
-----Inline Attachment Follows-----
|