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

michael rice nowgate at yahoo.com
Sun Nov 8 15:04:03 EST 2009

```Of course! Back to the drawing board.

Thanks,

Michael

--- On Sun, 11/8/09, Eugene Kirpichov <ekirpichov at gmail.com> wrote:

From: Eugene Kirpichov <ekirpichov at gmail.com>
Subject: Re: [Haskell-cafe] Area from [(x,y)] using foldl
To: "michael rice" <nowgate at yahoo.com>
Date: Sunday, November 8, 2009, 2:56 PM

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>

_______________________________________________

--
Eugene Kirpichov
Web IR developer, market.yandex.ru

-------------- next part --------------
An HTML attachment was scrubbed...