10.15. The Return of L-SystemsΒΆ

Let’s return to the L-systems we introduced in the previous chapter and introduce a very interesting new feature that requires the use of lists.

Suppose we have the following grammar:

X --> F[-X]+X
F --> FF

This L-system looks very similar to the old L-system except that we’ve added one change. We’ve added the characters ‘[‘ and ‘]’. The meaning of these characters adds a very interesting new dimension to our L-Systems. The ‘[‘ character indicates that we want to save the state of our turtle, namely its position and its heading so that we can come back to this position later. The ‘]’ tells the turtle to warp to the most recently saved position. The way that we will accomplish this is to use lists. We can save the heading and position of the turtle as a list of 3 elements. [heading x y] The first index position in the list holds the heading, the second index position in the list holds the x coordinate, and the third index position holds the y coordinate.

Now, if we create an empty list and every time we see a ‘[‘ we append the list that contains [heading, x, y] we create a history of saved places the turtle has been where the most recently saved location will always be at the end of the list. When we find a ‘]’ in the string we use the pop function to remove the the most recently appended information.

Let’s modify our drawLsystem function to begin to implement this new behavior.

When we run this example we can see that the picture is not very interesting, but notice what gets printed out, and how the saved information about the turtle gets added and removed from the end of the list. In the next example we’ll make use of the information from the list to save and restore the turtle’s position and heading when needed. We’ll use a longer example here so you get an idea of what the kind of drawing the L-System can really make.

Rather than use the inst string supplied here, use the code from the string chapter, and write your own applyRules function to implement this L-system. This example only uses 6 expansions. Try it out with a larger number of expansions. You may also want to try this example with different values for the angle and distance parameters.

Next Section - 10.16. Append versus Concatenate