[Haskell-cafe] Area from [(x,y)] using foldl
michael rice
nowgate at yahoo.com
Sun Nov 8 16:42:13 EST 2009
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 at yahoo.com> wrote:
From: michael rice <nowgate at yahoo.com>
Subject: Re: [Haskell-cafe] Area from [(x,y)] using foldl
To: "Chaddaï Fouché" <chaddai.fouche at gmail.com>
Cc: haskell-cafe at 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 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.
--
Jedaï
-----Inline Attachment Follows-----
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091108/cad0ff60/attachment-0001.html
More information about the Haskell-Cafe
mailing list