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

Casey Hawthorne caseyh at istar.ca
Sun Nov 8 18:44:03 EST 2009


On Sun, 8 Nov 2009 15:07:45 -0800 (PST), you wrote:

>Hi Casey,
>
>I was already aware of the translation thing, but didn't want to complicate.
>
>Lot's of ways to skin a cat. I wrote a Lispy solution, then had the feeling I could improve on it w/Haskell. Picking the right tool takes practice.
>
>Thanks,
>
>Michael

Since Haskell is a pure functional language, it adds lazy evaluation
as another tool to your modularity toolbox.

Lazy evaluation separates control from computation, so, if the
computation of sum is going off the rails (and I don't mean Ruby on
Rails), one can prematurely terminate the calculation, without
evaluating more points.


>
>--- On Sun, 11/8/09, Casey Hawthorne <caseyh at istar.ca> wrote:
>
>From: Casey Hawthorne <caseyh at istar.ca>
>Subject: Re: [Haskell-cafe] Area from [(x,y)] using foldl
>To: haskell-cafe at haskell.org
>Date: Sunday, November 8, 2009, 5:44 PM
>
>Sorry, I forgot to add that if the polygon is very far from the
>origin, you may have overflow or increased round off error; it is
>better to translate the polygon back to the origin, before doing the
>area calculation.
>
>
>How about these BETTER type signatures.
>
>-- Area of a Polygon
>    
>import Data.List
>
>type X = Double
>type Y = Double
>type Area = Double
>
>    
>poly1 = [(0,1),(5,0),(3,4)]::[(X,Y)]
>
>
>areaPoly :: [(X,Y)] -> Area
>
>
>areaPolyCalc :: (Area,(X,Y)) -> (X,Y) -> (Area,(X,Y))
>
>
>
>
><Spoiler Alert! -- Functions Below!>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>areaPoly (pt:pts) = 0.5 * (fst (foldl' areaPolyCalc (0,pt) pts))
>
>areaPolyCalc (sum,(x,y)) (xNext,yNext) = 
>            (sum + (x * yNext - xNext * y),(xNext,yNext))
--
Regards,
Casey


More information about the Haskell-Cafe mailing list