Alright already!!! Can we finally start to actually organize a picnic???
Yes! now that we can read and write SVG pictures, we're finally ready to start organizing a picnic!
First thing we'll want to do is break our city park into evenly-sized little lots for each picnickers to sit on- In order to do this, we'll first need some functions that can slice and dice big polygons into small polygons- The first of these functions is triangulate:
let triangulate :: Polygon -> [Polygon] triangulate (a:b:c:xs) = [a,b,c]:triangulate (a:c:xs) triangulate _ =  let triangles = concatMap triangulate park writeFile "tut2.svg" $ writePolygons (purple triangles)
Here's what the file tut2.svg will look like:
There's a few things i'll need to explain about the triangulate function...
First of all, you notice that this function is actually has two definitions, with different patterns to the left of the equal sign ((a:b:c:xs) and _) The way Haskell works is that it will try to match to the first pattern if it can. Then, if that fails, it'll go to the next one it finds.
In the first version of the function, it checks to see if the list of points has at least three points in it- As you can imagine, it's hard to triangulate something if you don't have at least three points. The colons in the (a:b:c:xs) expression let you pick the head item off of a list (or, for that matter, stick something on the head if we used it on the right side of the equation) so this pattern means we need the next three "heads" of the list to be 3 values a, b, and c. If we don't have three points, the second version of the function will match instead. (anything will match the underline character)
If we do find that we have three points, the first version of triangulate will make a triangle and will then recursively call itself to build more triangles. In a language like Haskell, which has no loops, these types of recursive functions that consumes lists are a classic design. Most of the time, however, we can avoid explicitly creating recursive functions like this by using list functions like map and folds, which we'll discuss later.
Using Haskell pattern matching and recursion, we can very elegantly express functions that process lists, like triangulate.
Polygon triangulation is actually slightly more complicated than our function suggests, because there's special procedures that would need to be followed to triangulate concave polygons... In this tutorial, we're skirting this issues by removing convex polygons when we draw our city park maps- That's why there's some oddball extra lines in the original park map.