[Haskell-cafe] Question on Exercise from SOE

Tom Pledger tpledger at ihug.co.nz
Sat Jul 3 19:55:06 EDT 2004

Nathan Weston wrote:

>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?


In this case polyArea is only consuming one element (v2) at a time, 
while examining v3. But the essential question still stands.

Two tricks come to mind.

Before folding. you could do something to vs, using zip or one of its 
friends, so that you get a list of pairs of successive vertices.

You could change "consume v2 while examining v3" to "consume v3 while 
remembering v2", and carry the last consumed vertex forward as part of 
the result type of the fold.


More information about the Haskell-Cafe mailing list