startshape realStart rule realStart { start { x 2 } } background { b -1 } rule start { terminal4 { r 12 } } rule start { terminal1 { r 12 } } rule start { terminal4 { r 12 } } rule start { terminal4 { r 12 } } rule start .05 { terminal2 { r 12 } } rule terminal4 { SQUARE { b 0.50 s .055 sat 0.40 hue 95 } SQUARE { b 1 s .055 a -.8 } train { x .06 } train { r 90 y .06 } train { r 180 x -.06 } train { r 270 y -.06 } } rule terminal2 2 { SQUARE { b 1 s .055 a -.85 } train { r 90 y .06 } train { r 270 y -.06 } } rule terminal2 1 { SQUARE { b 1 s .055 a -.8 } train { x .06 } train { r 90 y .06 } } rule terminal2 1 { SQUARE { b 1 s .055 a -.85 } train { x.06 } train { r 270 y -.06 } } rule terminal1 { CIRCLE { b 1 s .055 a -.9 } train { r 90 y .06 } } rule terminal1 { CIRCLE { b 1 s .055 a -.9 } train { r -90 y -.06 } } rule train 1 { CIRCLE { b 1 s .045 a -.9 } train { x .06 } } rule train 2 { terminal1 { } } rule train .02 { terminal2 { } } rule train .005 { terminal4 { } } rule train .03 { CIRCLE { b 1 s .03 a -.9 r -95 } }

Keith's Blog

A teen's .net musings


Posted on December 3, 2011 at 11:20 AM

Let me start with a bit of background. Processing is a library for Java that allows an almost sketching programming experience. It does this by simplifying the draw commands so that simple things like drawing a pixel are actually simple. This means that drawing more complex things is a lot simpler of a process. The original library can be found Here.

My new port of processing to F# is by no means a full port. I currently have a subset of it that includes most of the basic draw commands like rect, elipse, point, and line, but I do not have the complicated commands that deal with 3d graphics or transformations. Although it is a subset, I can still port with a high degree of efficiency the samples on the processing website. For example, the Distance2d sample source from the website is this:

float max_distance;

void setup() {
  size(200, 200); 
  max_distance = dist(0, 0, width, height);

void draw() 

  for(int i = 0; i <= width; i += 20) {
    for(int j = 0; j <= height; j += 20) {
      float size = dist(mouseX, mouseY, i, j);
      size = size/max_distance * 66;
      ellipse(i, j, size, size);

The equivalent f# code is this:

type Sample () = 
    inherit PApp()
    let mutable max = 0.0
    let min = 3
    override this.Setup () = 
        this.Size 200 200
        this.Fill 255
        max <- this.Dist(0,0,this.Width,this.Height)
    override this.Draw () =
        this.Background 51
        for x in [0..20..this.Width] do
            for y in [0..20..this.Height] do
                let size = this.Dist(this.MouseX,this.MouseY,x,y)
                let size = int(size/max * 66.0)
                let size = match size with
                           | x when x < min -> min
                           | _ -> size
                this.Ellipse x y size size

As you can see, the similarity is very apparent. Unfortunately although the code is the same, there are some differences. For instance in my version there is no anti-aliasing. This is because to get the speed I needed in drawing, I needed to use the writeable bitmap instead of the cleaner shape objects already implemented in silverlight. However there are some things that this gives that processing proper can’t do like discriminated unions, other language interop, and .net library support. I created this on a whim and it was surprisingly satisfying and easy to create the code with the F# Async operator. The core loop is simply an async expression with a while loop and a async sleep command. What this means is that I am able to do whatever I want and can be sure that I will be recalled in 1 60th of a second.

    member this.Show () =
        async {
            let lagging = ref false
            let draw () = lagging := true
                          pmouseX <- mouseX
                          pmouseY <- mouseY
                          lagging := false
            while true do
                do! Async.Sleep 16
                if clicked then
                    dispatch this.MousePressed
                    clicked <- false
                if released then
                    dispatch this.MouseReleased
                if setup then
                    if loop then
                        if not !lagging then
                            dispatch draw
                    elif redraw then
                        if not !lagging then
                            dispatch (fun () -> frameCount <- frameCount + 1)
                            dispatch draw
                            redraw <- false
        } |> Async.StartImmediate
        let app = new Application()
        app.Run(window) |> ignore

That is all I need and it runs perfectly. Now you may have noticed the dispatch method that I am using, all that does is take a function as a param and run it on the UI thread. That way, although I only access the variables from this function, I can be sure that there will be no collisions between threads.

    let dispatch (func:unit->unit) =
        window.Dispatcher.BeginInvoke(Action(fun _ -> func())) |> ignore

This in my opinion really showcases the brevity of the F# syntax and shows how fun a language it is to work with.

Well, 1 project down, 4 to go

F# Random Projects

Posted on November 28, 2011 at 9:25 PM

So… Its been a while…

In the time since I last posted (April, ouch) I have done many a programming project including a core wars implementation, a raycaster on the windows phone, an AI, and a port of the famous processing library to f#. I will try to post about them soon, but with school and copious amounts of homework, the likely hood of anything getting finished is very low. You may have noticed that I now have the new theme up and that, yes, it has crazy stuff going on in the background. What you are seeing is a fully working implementation of the context free js project in the background. It took forever and its cool, but I am still wondering if it was worth it. I had to lower the opacity of the text in the main portion of the blog to get the background to poke through and so I almost feel that it’s a bit busy (FIXED!!! I had to use rgba background instead of opacity, but now it works fine) Another interesting addition is the fact that my theme is now created using the razor render engine and 4.0 with 2.5.

The first topic that I want to cover is what f# is itself. F# is without a doubt the most amazing and complete programming language that I have ever had the pleasure to work with. It has the ability of c#, the brevity of ruby, and the power of lisp. It is a statically typed, functional, object oriented beast of a language with type inference, sequence expressions, and a plethora of interesting new data types. With all of this power and speed comes a new REPL command line that gives it the responsiveness and exploratory capabilities of the dynamic scripting languages. I believe without a doubt that this relatively new functional language is the salvation of the .net community and just what the doctor ordered.

Unfortunately I am one of the few who are willing and completely happy with completely switching cold turkey. Along with the age and functional nature of this gem of a language comes some, ahem, setbacks the biggest of which is a lack of tooling support. Although F# does have native .net support and the ability to run on silverlight and the phone, it does not have any of the xaml creation utilities that are a given in a native c# environment. The only project types that come out of the box for F# are a console app, .net library, and the tutorial. This alone is a great setback (or chance to learn how stuff works, depending on your point of view).

In my opinion although there are these difficulties, there is one feature that completely redeems the entire language: Discriminated Unions. These data types allow one to create a complete tree structure with a few lines. They are also useful with embedded dsls. This particular example is in my  AI script engine.

type Line =
    | Group of string * string list
    | Resp of int * string * string

let g name list = Group(name,list)
let r level pattern reply = Resp(level,pattern,reply)
let c level sentence = Resp(level,".+",sentence)

Here you can see that I create one type called line which has two subtypes: group and resp. The part after the initial declaration says what each type can contain. In the case of a group it contains a tuple with a string and a list of strings and with a response an int and two strings. What this allows me to do is create functions that take or return an object of type line, so the signature for g is:


So from the point of view of any other function it can treat the return value as a line and all that that implies. Now that is cool, but the true power of the discriminated union shows its ugly mug only when combined with the second most powerful construct in the F# language: Pattern Matching. The basic idea of pattern matching is that it breaks objects down by first type, and then internal parts. Let me explain, Say I have recursive data structure like a tree.

type Tree =
    | Branch of int * Tree * Tree
    | Leaf of int

This structure can then be summed via a simple recursive function

type Tree =
    | Branch of int * Tree * Tree
    | Leaf of int

let rec traverse tree =
    match tree with
    | Branch(value,left,right) -> value + traverse left + traverse right
    | Leaf(value) -> value

If this hasn’t blown your mind, then nobody can! Just to put this in perspective, this is the equivalent c# code. Brace yourself

public class TreeNode
    public int Value { get; private set; }
    public TreeNode Left { get; private set; }
    public TreeNode Right { get; private set; }
    public TreeNode(int value)
        Value = value;
    public TreeNode(int value, TreeNode left, TreeNode right)
        Left = left;
        Right = right;

    public static int Traverse(TreeNode node)
        if (node.Left != null && node.Right != null)
            return node.Value + Traverse(node.Left) + Traverse(node.Right);
            return node.Value;

That leaves us with a grand total of 28 to 8 lines. Even if you only count substantial lines, that gives 12 to 8. That is not to say that the F# is any worse to read like other succinct tar pits. It is simply a better and more dense way of representing the same information. One feature I did not describe with the unions is that they can have static and instance members which act just the same as objects and methods on normal c# classes. This allows you to have fundamentally different objects with similar methods on them and type checking.

Did I mention that I liked f#?