Phillip Trelford's Array

POKE 36879,255

F# in the Enterprise

Last night I popped down to Southampton to talk about F# in the Enterprise at the Developer South Coast meetup started by John McLoughlin. The group has grown quite a bit since last time I was down in 2010, and the hall was packed with about 50 members. It’s a really friendly group with a lot of interesting activities going on including hack weekends covering everything from electronics all the way through to games programming.


John contacted me after interest in a deep dive session on F# from the group.

Testimonials

At the start I covered a selection of testimonials captured on the F# Foundation site which gives some idea of where people are applying F# and the kind of benefits they’re seeing. .Net Rocks is another good source featuring interviews with F# developers talking about their experiences on projects, most recently Yan Cui from GameSys and Kit Eason on F# in Insurance.

order of magnitude increase in productivity, GameSys

performance is 10× better than the C++ that it replaces, Aviva

Take a look for yourself: http://fsharp.org/testimonials

Testing

The F# community has a strong testing focus with plenty of posts and libraries on the subject. As F# is a .Net language it works with all the regular .Net testing frameworks including NUnit, xUnit and MsTest:

open NUnit.Framework

let [<Test>] ``2 + 2 should equal 4`` () =
    Assert.AreEqual(4, 2 + 2)

Or using the popular FsUnit library you can make your assertions fluent:

[<Test>]
let ``2 + 2 should equal 4``() =    
    2 + 2 |> should equal 4

Stephen Swensen’s Unquote library takes a novel approach:

let [<Test>] ``2 + 2 = 4`` () =
    test <@ 2 + 2 = 5 @>

If a test fails unquote can help you uncover what went wrong:

Test 'Tests.2 + 2 = 4' failed: 

2 + 2 = 5
4 = 5
false

FsCheck a library based on QuickCheck is another F# library worth a look. FsCheck lets you fuzz test your functions which can help find those bugs that are harder to uncover with hand written unit tests. FsCheck can also be called from C#:

FsCheck

Types

Dependency injection (DI) is commonly employed in enterprise C# code. DI can make code more testable by injecting dependencies as interfaces to a class’s constructor:

public class HolidayService
{
    private readonly IFlightBooking _flights;
    private readonly IVillaBooking _villas;

    public HolidayService(IFlightBooking flights, IVillaBooking villas)
    {
        _flights = flights;
        _villas = villas;
    }

    public bool CanBook(DateTime date)
    {
        return _flights.Available(date) && _villas.Available(date);
    }
}

This can be expressed in F# as a class type:

type HolidayService(flights:IFlightBooking,villas:IVillaBooking) =
    /// Returns can book status
    member this.CanBook(date:DateTime) =       
       flights.Available(date) && _villas.Available(date)

The F# code generates the same IL as the C# code and works with all the major .Net dependency injection frameworks. I’ve personally used both Castle Windsor and more recently AutoFac.

If you’re using interfaces or abstract classes to inject dependencies you can provide mock instances when you test. This can be useful if for example you have code that interacts with a database or uses the current time.

F# 3 works seamlessly with all the major .Net mocking libraries like Rhino Mocks and Moq. If you’re looking for something that takes advantage of F#’s type inference features you might want to try out my imaginatively named Foq library which has a similar API to Moq:

let [<Test>] ``on no flights available you can't book`` () =
    let flights = 
        Mock<IFlightBooking>
            .Method(fun x -> <@ x.Available @>).Returns(false)
    let service = HolidayService(flights, mock())
    Assert.False(service.CanBook(any()))

That said it’s pretty easy to create an instance of an interface using F# built-in object expressions, so for many tasks a library is not needed:

{ new IDisposable with member __.Dispose() = printf "Disposed" }

And if you have interfaces with a single method you may just as well pass a function:

type HolidayService(hasFlight:DateTime->bool, hasVilla:DateTime->bool) =
    /// Returns can book status
    member this.CanBook(date:DateTime) = hasFlight(date) && hasVilla(date)

Type Providers

Type Providers are a feature unique to F# introduced in F# 3, that enable easy typed access to diverse data like databases, web services and even programming languages. In the presentation I showed Tomas Petricek’s World Bank sample running in Zach Bray’s FunScript. FunScript gives typed access to JavaScript libraries via a Type Provider to TypeScript and compiles F# code to JavaScript. The 80 line sample uses jQuery and HighCharts to show data pulled from the World Bank:

FunScript

For more example’s check out Don’s 12 Type Providers in pictures post.

Twitter

Thanks for all the great feedback on Twitter (here's just a few):

Tutorials

If you’re interested in learning F# I’d highly recommend the F# Koans and the online tutorials on the Try F# site:

image

Also check out the Progressive F# Tutorials in New York this September and London in late October:

Progressive FSharp Tutorials

Machine Learning from Disaster

Off the back of the popular Machine Learning hands on session at Skills Matter last month where we created a digit recognizer, last night we tackled a new dataset. Again we took a task from Kaggle’s online predictive modelling competitions. This time the data set was passenger details from the Titanic, with the task to analyse who was likely to survive.


Guided Task: http://trelford.com/titanic.zip (unblock the file, unzip to C:\titanic, load in VS2012 and run through the tasks in the titanic.fsx interactive F# script).

Kaggle provide a CSV file with the passenger details, we loaded this using FSharp.Data’s CSV provider which infers the fields and types of the data for you:

let [<Literal>] path = "C:/titanic/train.csv"
type Train = CsvProvider<path,InferRows=0>
type Passenger = Train.Row

let passengers : Passenger[] = 
    Train.Load(path).Take(600).Data 
    |> Seq.toArray

Then did some preliminary data analysis tasks looking at how well specific features predicted survival:

let females = passengers |> where female
let femaleSurvivors = females |> tally survived
let femaleSurvivorsPc = females |> percentage survived

Finally we used a provided decision tree learning algorithm for prediction:

let labels = [|"sex"; "class"|]

let features (p:Passenger) : obj[] = [|p.Sex; p.Pclass|]

let dataSet : obj[][] =
    [|for passenger in passengers ->
        [|yield! features passenger; 
          yield box (p.Survived = 1)|] |]

let tree = createTree(dataSet, labels)

I used the decision tree code from the Machine Learning in Action book porting the Python implementation to F#, here’s the gist of it. The Python Tools for Visual Studio (PVTS) came in handy for checking the outputs were the same on both implementations. Mathias Brandewinder has a great article on Decision Tree classification and also Random Forest classification in F# using the same Titanic data set. 

Again it was great to see a full house for the event with over 50 members in attendance:

full house

There’s a few more pictures from the event over on the Skills Matter Facebook page :)

Check out the F#unctional Londoners meetup page for upcoming meetings, the next one is 2 weeks on F# Mobile Apps. If you’re interested in more hands on sessions with F# I’d also highly recommend the Progressive F# Tutorials in New York this September and London in October, as there is still a great early bird rate:

miketempbannerprogfsharp-670x180px

We Jammin’

Last weekend I teamed up with other gamers for the Creative Assembly game jam at Rezzed. We had 9 hours to create a game, and were given the theme of the 80s at 9am on the Saturday morning. After some brainstorming we came up with the idea of a platform game that became an endless runner with rhythm and puzzles called We Jammin’:

hashtag

The main character is a skateboarder, collecting 80s artefacts to build up the volume on each track, while hitting mental blocks depletes the volume. All 4 tracks must reach the required volume level to complete a level:

sp3

Here's a short video of the game running in Unity:


 

Here’s the game presentations made to a packed audience on the Sunday afternoon (skip to 26:20 for We Jammin):



We had a lot of fun making the game and it was a great experience, particularly for my 11yo son Thomas who created sound effects and the base line for the game.

If you’d like to have a go at making a game in a day, check out London GameCraft, a free one day game jam at Skills Matter on Saturday the 10th August:

gamecraft