[Haskell-cafe] Question on Exercise from SOE
Nathan Weston
elbows at spamcop.net
Sat Jul 3 17:46:14 EDT 2004
I am learning haskell (and functional programming), from the School of
Expression book.
There's an exercise to rewrite the following function (for computing the area
of a polygon) using map, fold, etc:
data Shape = Polygon [Vertex]
area (Polygon (v1:vs)) = polyArea vs
where polyArea :: [Vertex] -> Float
polyArea (v2:v3:vs') = triArea v1 v2 v3 + polyArea (v3:vs')
polyArea _ = 0
My first thought is to use fold here, since this function accumulates a result
as it traverses the list. But fold consumes one element of the list at a
time, while area needs to examine the first three elements of the list, and
consume two of them at a time.
Is there a more general alternative to fold? Or is there some trick I'm
missing here?
Thanks,
Nathan
More information about the Haskell-Cafe
mailing list