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 Triangle (this)
  6. Dragon Curve
  7. Frac­tal Plant

Last time out we imple­mented the Koch Curve exam­ple from the L-System wikipedia page. Now, let’s con­tinue our jour­ney and see how we can imple­ment the Sierpinski Triangle exam­ple in Elm.

 

Example 5 : Sierpinski Triangle

First, let’s define our L-System:

image

Since we have done a lot of the heavy lifting in the last post (recall the Path module we created), we actually don’t have much to do here.

image

The only thing of interest here is that both ‘A’ and ‘B’ mean “draw forward”, but need to be represented different for the growth rules.

As far as I know, (please correct me in the comments if I’m wrong about this) there is no way to handle both symbols using case..of here, e.g.

case sym of

    ‘A’ | ‘B’ –> …

similar to how one would do in F#:

match sym of

| ‘A’ | ‘B’ –> …

| ‘+’ –> …

| ‘–‘ –> …

Hence why I opted for a multi-way if statement here instead.

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

sierpinski_tri_v1

 

But wait, the L-System wikipedia page also mentions a second way to draw the Sierpinski Triangle:

image

So, let’s implemented this as well, as v2.

image

When I used the suggested 120 degrees, I got an upside-down triangle. So instead, I used –120 degrees here:

image

Yup, it’s basically a carbon copy of the first version, except for a different value for angle  plus different symbols.

Why are the examples not consistent with the choice of symbols for “draw forward”? One wonders…

Anyhow, 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-System.

Source Code (here, here)

 

 

Next : Dragon Curve

 

Links

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy