Sunday, 6 June 2010

A dragon curve in 17 lines of F#

Dragon curves are a family of self-similar fractal curves. The following 17-line F# program uses Windows Presentation Foundation to visualize the results of a simple recursively-constructed dragon curve:

open System.Windows open System.Windows.Media let m = Matrix(0.0, 0.5, -0.5, 0.0, 0.0, 0.0) let step segs = seq { for a: Point, b: Point in segs do let x = a + 0.5 * (b - a) + (b - a) * m yield! [a, x; b, x] } let rec nest n f x = if n=0 then x else nest (n-1) f (f x) [<System.STAThread>] do let ps = nest 14 step (seq [Point(0., 0.), Point(1., 0.)]) let d = Vector(Seq.min[for a, b in ps -> min a.X b.X], Seq.min[for a, b in ps -> min a.Y b.Y]) let lineTo p = (LineSegment(p, true) :> PathSegment) let path = Shapes.Path(Stroke=Brushes.Black, StrokeThickness=0.003) path.Data <- PathGeometry[for a, b in ps -> PathFigure(a-d, [lineTo(b-d)], false)] (Application()).Run(Window(Content=Controls.Viewbox(Child=path))) |> ignore

This program produces the following output:

6 comments:

Benjol said...

What dlls do I need to reference?

Flying Frog Consultancy Ltd. said...

@Benjol: The usual WPF ones: System.Xaml, PresentationCore, PresentationFramework and WindowsBase.

mehdi.asgari said...

Also, one must add this line to the top of code:
open System.Windows.Shapes

Art said...

Hi Benjol and Mehdi.
I got it working with additon of "The usual WPF" Referneces. Didn't need the added code to open Shapes ...?

My interest is using F# and WPF (and Silverlight) for art animation and video.

Chris said...

Odd, when using F# v2.0 and vs2005, it complains that the yeild! is a syntax error.

Any idea's what could be wrong?

Flying Frog Consultancy Ltd. said...

@Chris: F# 2.0 works with VS 2005?! :-)