Elm – fun with L-System (Part 3)

Series:

  1. Algae
  2. Pythago­ras Tree
  3. Can­tor Dust (this)
  4. Koch Curve
  5. Sier­pin­s­ki Tri­an­gle
  6. Drag­on Curve
  7. Frac­tal Plant

Last time out we imple­ment­ed the Pythago­ras Tree exam­ple from the L-Sys­tem wikipedia page. Now, let’s con­tin­ue our jour­ney and see how we can imple­ment the Can­tor Dust exam­ple in Elm.

Example 3 : Cantor Dust

First, let’s define our L-Sys­tem:

image

The inter­est­ing thing about this exam­ple is that we need to draw, not only the cur­rent gen­er­a­tion, but also all the pre­ced­ing gen­er­a­tions too.

So I had to approach things slight­ly dif­fer­ent­ly, and instead of deal­ing with a Signal(State), I need a Signal(List(State)):

image

This sig­nal of List(State) is then passed to the dis­play func­tion (along with the dimen­sion of the win­dow):

image

 

We can use rec­tan­gle to rep­re­sent the indi­vid­ual bars, and for my screen 25 pix­els seems to be a good height.

image

For each gen­er­a­tion we want to place them some dis­tance apart. That is to say that the state for each gen­er­a­tion should have a stepped Y posi­tion.

image

so now, we need to add a draw­State func­tion that will take in:

  • the width of the win­dow;
  • the y posi­tion for its rec­tan­gles; and
  • the state it needs to draw

and return a list of rec­tan­gles for that state.

image

You may remem­ber the fol­low­ing para­graph from Part 2:

image

So to work out the x posi­tions of the first rec­tan­gle for this state, we have this slight­ly dubi­ous look­ing line of code:

image

image

and the next block of code gen­er­ates the x posi­tions for all the rec­tan­gles:

image

 

Run­ning this exam­ple in Elm Reac­tor I can get the demo to gen 8, after that it takes notice­ably longer to ren­der and the bars are so thin that they’re bare­ly vis­i­ble.

image

 

Live Demo (here)

Use LEFT and RIGHT arrow keys to evolve/devolve the L-Sys­tem.

 

Source Code (here)

 

Next : Koch Curve

Links