Gram's blog has been pretty fun to follow. Like with Project Euler, I constantly want to implement each thing he talks about (e.g. Monadic Coconuts, Towers of Hanoi).

Here now is "The Wondering Ant":

open System.Drawing

open System.Windows.Forms


let rec ant (x, y) (dx, dy) g i =

    let g' = Array2D.mapi (fun x' y' c -> if x = x' && y = y' then not c else c) g

    let turn d l r = if d <> 0 then 0 else if g.[x, y] then l else r

    let dx' = turn dx dy -dy

    let dy' = turn dy -dx dx

    if i = 0 then g' else ant (x + dx', y + dy') (dx', dy') g' (i - 1)


let w = 200

let h = 200

let grid = ant (100, 100) (-1, 0) (Array2D.create w h false) 11000


let form = new Form(Text = "Ant", ClientSize = new Size(w, h), Visible = true)

form.Paint.Add(fun a ->

    let b = new Bitmap(w, h)

    Array2D.iteri (fun x y c -> if c then b.SetPixel(x, y, Color.Black)) grid

    a.Graphics.DrawImage(b, 0, 0))