Draw the Sierpinski triangle

In this exercise you will draw a famous fractal, the
http://en.wikipedia.org/wiki/Sierpinski_triangle
First look up the command for drawing a

Polygon

and read the help page. The following call to Polygon draws an equilateral triangle.

p=Polygon[{{1,0},{0,Sqrt[3]},{-1,0}}];Graphics[p]

Study this call carefully, make sure you understand it thoroughly. Next write a function called triangle with arguments llx and lly for the lower left x and y coordinates, and base for the base. Use Module. It is essential that you use only local variables for the coordinates of the points of the triangle. This function should return the polygon of the above equilateral triangle.

Test your function with

Graphics[triangle[-1,0,2]]

The following call to Polygon draws a red colored equilateral triangle.

p=Polygon[{{1,0},{0,Sqrt[3]},{-1,0}}];Graphics[{Red,p}]

Next write a function called colortriangle with an additional color argument.

Test your function with

Graphics[colortriangle[-1,0,2,Red]]

Next use this function colortriangle as starting point for a new function called innertriangle with the same four arguments (llx and lly for the lower left x and y coordinates, base and color). The function innertriangle draws a Sierpinski triangle of depth 1. It is essential that you use only local variables for the coordinates of the points of the two triangles. In the example below first a black outer triangle was drawn, followed by red inner triangle.

Test your function with

Graphics[innertriangle[-1,0,2,Red]]

To annotate it use :

{Annotation[Graphics[innertriangle[-1,0,2,Red]],"Sierpinski triangle of depth 1","Mouse"],Dynamic[MouseAnnotation[]]}

Next we will use recursion to draw a Sierpinski triangle of depth d. E.g. for d = 2, and white color :

Graphics[Sierpinski[-1,0,2^2,White]]

Write your own Sierpinski function to be called with the same four arguments (llx and lly for the lower left x and y coordinates, base and color). Use the same kind of recursive algorithm as in the code for drawing Pythagoras’ tree. It is essential that you use only local variables for the objects that constitute the inner triangles.

First test whether you can produce the above figure, and then test it with

Graphics[Sierpinski[-1,0,2^4,White]]

Local versus global variables

This exercise offers the possibility to investigate the fundamental differences of local and global variables. Investigate what happens when you use global names for the objects that constitute the inner triangles in a modified version of the Sierpinski function. Explain what happens.