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

Eugene Kirpichov ekirpichov at gmail.com
Sun Nov 8 14:56:02 EST 2009


The type of foldl is:
(b -> a -> b) -> b -> [a] -> b

What do you expect 'a' and 'b' to be in your algorithm?

2009/11/8 michael rice <nowgate at yahoo.com>

> Here's an (Fortran) algorithm for calculating an area, given  one
> dimensional
> arrays of Xs and Ys. I wrote a recursive Haskell function that works, and
> one using
> FOLDL that doesn't. Why would Haskell be "expecting" (t, t) out of ((*)
> (xold-x) (yold+y))?
>
> Michael
>
> ====================
>
>    AREA = 0.0
>    XOLD = XVERT(NVERT)
>    YOLD = YVERT(NVERT)
>    DO 10 N = 1, NVERT
>            X = XVERT(N)
>            Y = YVERT(N)
>            AREA = AREA + (XOLD - X)*(YOLD + Y)
>            XOLD = X
>            YOLD = Y
> 10 CONTINUE
>
>    AREA = 0.5*AREA
>
> ====================
>
> 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>
>
> ====================
>
> area :: [(Double,Double)] -> Double
> area p = foldl (\ (xold,yold) (x,y) -> ((*) (xold-x) (yold+y))) 0 ((last
> p):p)
>
>
> Prelude> :l area
> [1 of 1] Compiling Main             ( area.hs, interpreted )
>
> area.hs:29:40:
>     Occurs check: cannot construct the infinite type: t = (t, t)
>       Expected type: (t, t)
>       Inferred type: t
>     In the expression: ((*) (xold - x) (yold + y))
>     In the first argument of `foldl', namely
>         `(\ (xold, yold) (x, y) -> ((*) (xold - x) (yold + y)))'
> Failed, modules loaded: none.
> Prelude>
>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>


-- 
Eugene Kirpichov
Web IR developer, market.yandex.ru
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091108/b08ae3f2/attachment.html


More information about the Haskell-Cafe mailing list