An F# Ant Colony Simulation in Silverlight 4.0 with Dynamic ... I’ve been enviously watching Phillip Trelford publish excellent F# games all week and tonight I just couldn’t stand it anymore. I stayed in, rolled up my sleeves and ported the very same ant colony simulation I used in my CUFP workshop to Silverlight 4.0. Wow, just look at those little guys go at it. Silverlight sure is pretty! As you might have noticed by the big white “Click To Load Custom AI” message, you can also compile your own AI and battle it out with what I’ve included here. To make things easy I’ve provided a ready to go solution. Simply load it up, compile it and select the compiled DLL. Once you’ve loaded your AI the game will immediately start. If your interested in the gory details of the simulation itself, I’ve put up a github repository with the entirety of the code. Cheers! Update: I’ve mucked with a few things. Performance-related features in F# and C#
Lorenz attractor. The Lorenz attractor is a fractal derived from the trajectory of a 3-dimensional dynamical system that exhibits chaotic flow. This blog post describes a 35-line program that computes trajectories of this attractor and visualizes them as a beautiful whisp using Windows Presentation Foundation: The program is as follows: > #r "PresentationCore.dll";; > #r "PresentationFramework.dll";; > #r "WindowsBase.dll";; > #r "System.Xaml.dll";; > let trajectory f (x, y, z) dt n = let s, b, p = 10.0, 8.0 / 3.0, 28.0 let mutable x = x let mutable y = y let mutable z = z let a = Array.zeroCreate n for i=0 to n-1 do a.
The trajectory function generates an array derived from the coordinates along a trajectory with the given starting position. The whisp function computes a trajectory with a slightly randomized starting position and generates a WPF PathGeometry. SEO Analysis in F#, a friendly application. Last time, we provided the components to actually make the SEO helpers into a real application. This time, we make the application more friendly. In particular : default files and directories are created if they don’t exist yet. Then, instead of being forced to use a command window, this time, double clicking will suffice.
This will also allow us to see how to use events and Winforms (yup, no WPF !) , and how to use functions to make form building a tad quicker. We still compile the application as a console application for two reasons : first, this mean we can still use the command-line calls (particularly useful through .bat files when the same arguments are used all the time) ; secondly, the info (fetching this and that) is displayed in the console when the application runs. Application. Generically Constraining F# Generic constraints inside .NET has always been a fun enterprise, especially given how C# handles them There has been some discussion on Jon Skeet’s blog about the fact that C# does not allow for generic constraints referring to a number of types.
These include: System.Array System.Delegate System.Enum System.Object System.ValueType This is indeed a bit unfortunate, as it limits some of the more interesting applications. The example Jon shows is indeed illegal in C#: public static T[]GetValues<T>() where T : struct, System.Enum { return (T[]) Enum.GetValues(typeof(T)); } However, as Jon correctly points out, this is indeed supported by the CLR directly. Let’s first look at our F# implementation.
Namespace Codebetter.Constraints module Constraint = open System let getValues<'a, 'b when 'a : enum<'b>>() = Enum.GetValues(typeof<'a>) :? As we can see from the above code, it’s rather straight forward. This will compile just as our previous example did. And the calling C# code: F#: Pipelined Monads. #light type Definition = unit type internal ModelResultCatch<'T> = | ModelResultOK of 'T | ModelResultException of System.Exception type ModelResult<'T> = | ModelValue of 'T | DelayedModelValue of (unit->ModelResult<'T>) | Collision of Definition*Definition | UndefinedScope of string list | InvalidContainment of Definition*Definition | InvalidOperation of string member s.IsDelayed () = match s with | DelayedModelValue(_) -> true | _ -> false member s.IsException () = | ModelValue(_) -> false | _ -> true member s.Get() = | ModelValue(m) -> m | _ -> failwith "invalid operation" member s.Complete() = let rec loop x = match x with | DelayedModelValue work -> loop (work()) | _ -> x loop s member s.CastException<'U> () = | ModelValue(_) -> failwith "invalid cast" | DelayedModelValue(_) -> failwith "invalid cast" | Collision(d1,d2) -> ModelResult<'U>.Collision(d1,d2) | UndefinedScope(s) -> ModelResult<'U>.UndefinedScope(s) | InvalidContainment(d1,d2) -> ModelResult<'U>.InvalidContainment(d1,d2) module ModelResult = catch (e)
Units of Measure in F#: Part One. Do you remember NASA's Mars Climate Orbiter? It was lost in September 1999 because of a confusion between metric and so-called "English" units of measurement. The report into the disaster made many recommendations. In all likelihood, the accident could have been prevented if the NASA engineers had been able to annotate their program code with units, and then employed static analysis tools or language-level type-checking to detect and fix any unit errors. Of course, the languages that NASA used had no language or tool support for units.
As recently announced in the September 2008 F# CTP (Community Technical Preview), the F# programming language now has full support for static checking and inference of units-of-measure. We'll start more traditionally, with units for mass, length and time. Here, the Measure attribute tells F# that kg, s and m aren't really types in the usual sense of the word, but are used to build units-of-measure. Now we can do some physics! Magic! Summing up. Catamorphisms, part one. (Read this blog entry at a pace which is appropriate for you.
Some readers will find this mostly old-hat, whereas others will find it rough going at parts. I encourage you to take a break and try out the code examples, if that helps you out.) I would like to discuss catamorphisms. A catamorphism is a generalization of a fold on lists to an arbitrary data type. So for today’s blog entry, let’s review lists and folds. We’ll also end up discussing continuations as a cool technique for preserving tail-recursion in certain kinds of folds. Lists and folds If you’ve taken a CS class that was some sort of “introduction to functional programming”, you almost surely started out writing recursive functions that operated on lists. // SumList : list<int> -> intlet rec SumList l = match l with | h :: t -> h + SumList t | [] -> 0 printfn "%d" (SumList [1; 2; 3; 4]) // prints 10 But then the instructor has you sum the list of numbers from 1 to 100000 and *kaboom* you blow the stack.
To be continued… Correct by Construction in F# Correct by Construction in F# Jomo Fisher—a theme in the design of the F# language is that problems in the code are revealed as compilation errors. Consider this C# code which is used to compose a courteous letter to a customer: enum Courtesy { Mr, Ms, Dr } class Customer { public Courtesy Courtesy { get; set; } public string Name { get; set; } class Letter { public string Introduction { get; set; } public string Body { get; set; } static Letter Correspond(Customer customer, string message) { switch (customer.Courtesy) case Courtesy.Mr: return new Letter { Introduction = "Mr.
" + customer.Name, Body = message }; case Courtesy.Ms: return new Letter { Introduction = "Ms. " + customer.Name, return null; This compiles without errors despite having some problems (can you spot them?) I want to stop now and claim that I’m not picking on C# which is a wonderful language. Now, transliterate the code above into F#: #light type Courtesy = Mr | Ms | Dr type Customer = { Courtesy:Courtesy Name:string type Letter = { Using computation expressions to control monitor locks.