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

Chaddaï Fouché chaddai.fouche at gmail.com
Mon Nov 9 03:49:36 EST 2009


On Sun, Nov 8, 2009 at 10:30 PM, michael rice <nowgate at yahoo.com> wrote:
>
> 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
>
>
This function is almost correct except you got your priorities wrong :
application priority is always stronger than any operator's so "area' (last
p):p" is read as "(area' (last p)) : p"... Besides your second pattern is
also wrong, the correct code is :

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

-- 
Jedaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091109/9ca89309/attachment-0001.html


More information about the Haskell-Cafe mailing list