## Fun with turtle-graphics in F#

Posted by Brian on April 16, 2010

Once you have the mini LOGO implementation from my previous blog entry/screencast, it’s easy to start creating pretty fractals, like the Koch Snowflake:

The idea is simple; we start with a basic shape, such as an equilateral triangle:

let koch1 = [ Fwd 243; Right 120; Fwd 243; Right 120; Fwd 243 ]

and then we replace each “Fwd” segment with a more complex bit. Here’s the Koch translation in F#:

let kochChange(drawing) = seq { for cmd in drawing do match cmd with | Fwd n -> let x = n/3 yield Fwd x yield Left 60 yield Fwd x yield Right 120 yield Fwd x yield Left 60 yield Fwd x | c -> yield c }

That is, each time we encounter a “Fwd” segment, we replace it with LOGO code that does a little triangular sidestep around the middle third of the segment. Every other command “c” is just kept as-is.

Then we can repeatedly apply this function to get more and more detail. The picture above was created with:

let DRAWING = koch1 |> kochChange |> kochChange |> kochChange |> Seq.append [PenUp; Left 145; Fwd 120; Right 145; PenDown]

that is, three iterations of “kochChange” applied to the initial triangle (where the bit after “Seq.append” is just to move the turtle to a better initial starting position, so the drawing will all fit within the bounds of my canvas).

Pretty fun for 15 lines of code!

Here’s another pretty one:

The code for it is:

let rec Dragon1 size level = seq { if level > 0 then yield! Dragon (size*707/1000) (level-1) yield Left 90 yield! Dragon1 (size*707/1000) (level-1) else yield Fwd size } and Dragon size level = seq { if level > 0 then yield! Dragon (size*707/1000) (level-1) yield Right 90 yield! Dragon1 (size*707/1000) (level-1) else yield Fwd size } let DRAWING = Dragon 800 14

and it is __fascinating__ to watch it develop in real time on the screen.

Pretty fun for 17 lines of code!

Just imagine what you can do if you add color!

One reason I love F# is that it is just *so easy* to do all this stuff. I coded the LOGO implementation (less than 100 lines) on a whim for the backdrop of my prior screencast. And I wrote this blog entry on fractals for an hour early this morning because I was having trouble sleeping. Perhaps the hypnotic dancing turtle will lull me back to sleep…

## Michael said

I can\’t wait to get into this, I love how you have brought LOGO back into my life.