Previously, to draw the Hilbert Curve and the Peano Curve, we designed an explicit algorithm that recursively defines the shape of the curve. If we want to generalize this recursive construction, we end up with an L-System which can draw a whole bunch of fractals.
What is an L-System?
A Lindenmayer-System (L-System) is a set of string rewriting rules. You start with a string of letters, and apply each applicable rule to transform them into different letters. Let’s look at an example:
A // this is the axiom (start symbol of your grammar)
A=+B-A-B+ // rule for A
B=-A+B+A- // rule for B
The start of the derivation is the symbol A, and it has two rules, one for A and one for B. We allow some letters to not have a rule, like ‘+’ and ‘-‘, these simply stay unchanged in the derivations. Let’s look at the first three iterations:
Iteration 0: A // start symbol
Iteration 1: +B-A-B+
Iteration 2: + -A+B+A- - +B-A-B+ - -A+B+A- +
Iteration 3: +-+B-A-B++-A+B+A-++B-A-B+--+-A+B+A--+B-A-B+--A+B+A-+--+B-A-B++-A+B+A-++B-A-B+-+
For the first iteration we simply apply the first rule for ‘A’, in the second iteration we have to apply the rules for B,A,B again, and so on.
Mapping the strings to fractals
Maybe surprisingly, L-Systems are one of the best ways to draw fractals, due to their recursive nature. To get from an L-System to a fractal, you imagine you start with a pen (or a turtle) on a piece of paper, and interpret the string’s letters in some predefined way. In our example above, if A and B both mean draw a straight line of constant length forward, and +/– mean turn left/right by 60°, then the resulting drawings from the strings of our iterations approximate the Sierpinski triangle.
You can play around with an L-System below by changing its production rules or the drawing interpretation of the letters, and see if you can come up with any interesting shapes. There are a some common fractals already defined under “Presets”.