Elm – fun with L-System (Part 5)

Series:

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

Last time out we imple­mented the Koch Curve exam­ple from the L-Sys­tem wikipedia page. Now, let’s con­tinue our jour­ney and see how we can imple­ment the Sier­pin­s­ki Tri­an­gle exam­ple in Elm.

 

Example 5 : Sierpinski Triangle

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

image

Since we have done a lot of the heavy lift­ing in the last post (recall the Path mod­ule we cre­at­ed), we actu­al­ly don’t have much to do here.

image

The only thing of inter­est here is that both ‘A’ and ‘B’ mean “draw for­ward”, but need to be rep­re­sent­ed dif­fer­ent for the growth rules.

As far as I know, (please cor­rect me in the com­ments if I’m wrong about this) there is no way to han­dle both sym­bols using case..of here, e.g.

case sym of

    ‘A’ | ‘B’ –> …

sim­i­lar to how one would do in F#:

match sym of

| ‘A’ | ‘B’ –> …

| ‘+’ –> …

| ‘–‘ –> …

Hence why I opt­ed for a mul­ti-way if state­ment here instead.

Here’s how it looks, feel free to try it out your­self via the live demo links below.

sierpinski_tri_v1

 

But wait, the L-Sys­tem wikipedia page also men­tions a sec­ond way to draw the Sier­pin­s­ki Tri­an­gle:

image

So, let’s imple­ment­ed this as well, as v2.

image

When I used the sug­gest­ed 120 degrees, I got an upside-down tri­an­gle. So instead, I used –120 degrees here:

image

Yup, it’s basi­cal­ly a car­bon copy of the first ver­sion, except for a dif­fer­ent val­ue for angle  plus dif­fer­ent sym­bols.

Why are the exam­ples not con­sis­tent with the choice of sym­bols for “draw for­ward”? One won­ders…

Any­how, here’s how it looks, which you can also try out via the live demo links below.

sierpinski_tri_v2

 

Live Demo (here, here)

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

Source Code (here, here)

 

 

Next : Drag­on Curve

 

Links