Phillip Trelford's Array

POKE 36879,255

Method Stubs

I’ve spent the last 2-days of this week on a hands on TDD & Refactoring workshop ran by Jason Gorman. The course comprises of short exercises that you tackle in pairs. The provided machines came with Visual Studio 2010 installed so for most of the exercises my programming pair, Martin Trojer and I, used Visual F#.

One of the exercises was to implement a fictional holiday booking system that would connect to an external flight booking system and an external villa booking system. Holidays for a particular week of the year may only be booked if flights are available and one or more villas. The idea for the exercise was to test the holiday booking system using stubs for the flight and villa booking systems.

Being a Test Driven Development (TDD) course we Test First and Assert First, i.e. we write the test and the assertion before the code to implement the test:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    // ...
    Assert.AreEqual(holidays, [])

Another practice in XP/TDD is to write the simplest code that will make the test pass. In this case the simplest thing seemed to be to implement a function that gets the available holidays for a specific week given functions that determine flight and villa availability:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    let holidays = 
        getAvailableHolidays (isFlightAvailable, getAvailableVillas) (2,2013)
    Assert.AreEqual(holidays, [])

Now we implement the functions isFlightAvailable and getAvailableVillas as stubs:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    let isFlightAvailable _ = false
    let getAvailableVillas _ = ["Mountain Dew"]
    let holidays = 
        getAvailableHolidays (isFlightAvailable, getAvailableVillas) (2,2013)
    Assert.AreEqual(holidays, [])

With the stubs in place we can make the test fail:

let getAvailableHolidays (isFlightAvailable, getAvailableVillas) (week,year) = 
   getAvailableVillas (week,year)

The test fails because we are not checking flight availability. To make the test pass:

let getAvailableHolidays (isFlightAvailable, getAvailableVillas) (week,year) = 
   if isFlightAvailable (week,year) then getAvailableVillas (week,year)
   else []

Our first test passed. Time to refactor. In our test there is some code duplication, the stub functions isFlightAvaialble and getAvailableVillas always return the same value. We can create a method to encapsulate this:

let inline always value _ = value

Then we can use partial application to define a function getHolidaysWhenNoFlights:

[<Test>]
let ``when no flights are available then no holidays are available`` () =
    let getHolidaysWhenNoFlights = 
        getAvailableHolidays (always false, always ["Mountain Dew"])
    let holidays = getHolidaysWhenNoFlights (10,2012)
    Assert.AreEqual(holidays, [])

On to the next test case (which unfortunately passes immediately as the system has now been implemented):

[<Test>]
let ``when flights are available but no villas then no holidays`` () =
    let getHolidaysWhenNoVillas = 
        getAvailableHolidays (always true, always [])
    let holidays = getHolidaysWhenNoVillas (10,2012)
    Assert.AreEqual(holidays, [])

And so on:

[<Test>]
let ``flights and a villa are available then a holiday is available`` () =
    let getHolidays = 
        getAvailableHolidays (always true, always ["Mountain Dew"])
    let holidays = getHolidays (10,2012)
    Assert.AreEqual(holidays.[0], "Mountain Dew")

In F# I find myself starting with functions and then moving to classes if necessary. In C# and Java it seems people tend to start with classes, perhaps because refactoring from a static method to a class is felt to be hard. In F# it’s almost as easy as changing the let keyword to type, and declaring a member. So starting with our function to get available holidays:

let getAvailableHolidays (isFlightAvailable, getAvailableVillas) (week,year) = 
   if isFlightAvailable (week,year) then getAvailableVillas (week,year)
   else []

Refactored to a class:

type AvailableHolidays (isFlightAvailable, getAvailableVillas) = 
    member this.Get(week,year) =
        if isFlightAvailable (week,year) then getAvailableVillas (week,year)
        else []

Just before we ran out of time for this exercise we came up with a simple implementation for spying on method calls:

type Recorder () =
    let mutable xs = []
    member recorder.Record(x) = xs <- box x :: xs
    member recorder.Values = xs

let inline spy (recorder:Recorder) f = fun ps -> recorder.Record(ps); f ps

Which allowed us to check if a the flight booking system is being called with the correct values:

[<Test>]
let ``the flight availability system is passed the correct date`` () =
    let recorder = Recorder ()
    let isFlightAvailableSpy = spy recorder (always true)
    let getHolidays = 
        getAvailableHolidays (isFlightAvailableSpy, always [])
    let holidays = getHolidays (12,2012)
    Assert.AreEqual(recorder.Values,[12,2012])

So no frameworks required for either stubs or spies! .

Overall I felt a function based approach to TDD using F# worked very well, and resulted in a very simple solution.

Progressive F# Tutorials 2011

Last week’s 2-track Progressive F# Tutorials conference seems to have gone pretty well:

Possibly the best Skills Matter event I have attended

progfsharp11

You can see pictures from the event over on the Skills Matter Flickr stream:

Don Syme, Phil Trelford, Mark SeemanChris MarinosKit Eason, Martin Trojer, Don SymeTomas Petricek

Skills Matter also have Videos Podcasts of all the sessions including Don Syme’s keynote:

This was followed by an excellent Tennis Kata in the Programming with the Stars session performed by Mark Needham and Mark Seeman, first in C# and then F#.

wimbledon

Don posted this solution on F# Snippets which is pretty close the 2 Mark's vesion:

 1: /// The two players
 2: type Player = A | B
 3: 
 4: /// The point score in for a player in a game
 5: type PlayerPoints = Zero | Fifteen | Thirty | Forty 
 6: 
 7: /// The score of a game
 8: type Score = 
 9:     | Points of PlayerPoints * PlayerPoints 
10:     | Advantage of Player 
11:     | Deuce 
12:     | Game of Player
13: 
14: /// Compute the next score in a game 
15: let nextPointScore a = 
16:     match a with 
17:     | Zero -> Fifteen
18:     | Fifteen -> Thirty
19:     | Thirty -> Forty
20:     | Forty -> failwith "what??"
21: 
22: /// Check if we've reached deuce
23: let normalize score = 
24:     match score with 
25:     | Points(Forty,Forty) -> Deuce
26:     | _ -> score
27: 
28: /// Score a point in a game
29: let scorePoint score point =
30:     match score, point with 
31:     | Advantage player1, player2 when  player1 = player2 -> Game player1
32:     | Advantage player1, player2 -> Deuce
33:     | Deuce, player -> Advantage player
34:     | Points(Forty, _), A -> Game A
35:     | Points(_, Forty), B -> Game B
36:     | Points(a, b), A -> normalize (Points (nextPointScore a, b))
37:     | Points(a, b), B -> normalize (Points (a, nextPointScore b))
38:     | Game _ , _ -> (* printfn "the game is over!"; *) score
39: 
40: /// Score a whole game, where a game is a sequence of points
41: let scoreGame (points: seq<Player>) = 
42:     Seq.scan scorePoint (Points(Zero,Zero)) points
union case Player.A: Player
union case Player.B: Player
type PlayerPoints =
  | Zero
  | Fifteen
  | Thirty
  | Forty

Full name: Snippet.PlayerPoints

  type: PlayerPoints
  implements: System.IEquatable<PlayerPoints>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<PlayerPoints>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable


The point score in for a player in a game
union case PlayerPoints.Zero: PlayerPoints
union case PlayerPoints.Fifteen: PlayerPoints
union case PlayerPoints.Thirty: PlayerPoints
union case PlayerPoints.Forty: PlayerPoints
type Score =
  | Points of PlayerPoints * PlayerPoints
  | Advantage of Player
  | Deuce
  | Game of Player

Full name: Snippet.Score

  type: Score
  implements: System.IEquatable<Score>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Score>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable


The score of a game
union case Score.Points: PlayerPoints * PlayerPoints -> Score
union case Score.Advantage: Player -> Score
type Player =
  | A
  | B

Full name: Snippet.Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable


The two players
union case Score.Deuce: Score
union case Score.Game: Player -> Score
val nextPointScore : PlayerPoints -> PlayerPoints

Full name: Snippet.nextPointScore

Compute the next score in a game
val a : PlayerPoints

  type: PlayerPoints
  implements: System.IEquatable<PlayerPoints>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<PlayerPoints>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val failwith : string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
val normalize : Score -> Score

Full name: Snippet.normalize

Check if we've reached deuce
val score : Score

  type: Score
  implements: System.IEquatable<Score>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Score>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val scorePoint : Score -> Player -> Score

Full name: Snippet.scorePoint

Score a point in a game
val point : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val player1 : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val player2 : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val player : Player

  type: Player
  implements: System.IEquatable<Player>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<Player>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val b : PlayerPoints

  type: PlayerPoints
  implements: System.IEquatable<PlayerPoints>
  implements: System.Collections.IStructuralEquatable
  implements: System.IComparable<PlayerPoints>
  implements: System.IComparable
  implements: System.Collections.IStructuralComparable
val scoreGame : seq<Player> -> seq<Score>

Full name: Snippet.scoreGame

Score a whole game, where the game is represented as a sequence of points
val points : seq<Player>

  type: seq<Player>
  inherits: System.Collections.IEnumerable
Multiple items
val seq : seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------

type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>

  type: seq<'T>
  inherits: System.Collections.IEnumerable
module Seq

from Microsoft.FSharp.Collections
val scan : ('State -> 'T -> 'State) -> 'State -> seq<'T> -> seq<'State>

Full name: Microsoft.FSharp.Collections.Seq.scan
val game1 : seq<Player>

Full name: Snippet.game1

  type: seq<Player>
  inherits: System.Collections.IEnumerable


A sample game - A wins every point
val game2 : seq<Player>

Full name: Snippet.game2

  type: seq<Player>
  inherits: System.Collections.IEnumerable


A sample game - A and B swap points indefinitely
val game3 : seq<Player>

Full name: Snippet.game3

  type: seq<Player>
  inherits: System.Collections.IEnumerable


A sample game - A and B trade points but A wins more points than B
val truncate : int -> seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.truncate
val toList : seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.Seq.toList
val randomGame : int -> seq<Player>

Full name: Snippet.randomGame

Generate a random game
val i : int

  type: int
  implements: System.IComparable
  implements: System.IFormattable
  implements: System.IConvertible
  implements: System.IComparable<int>
  implements: System.IEquatable<int>
  inherits: System.ValueType
val rnd : System.Random
namespace System
type Random =
  class
    new : unit -> System.Random
    new : int -> System.Random
    member Next : unit -> int
    member Next : int -> int
    member Next : int * int -> int
    member NextBytes : System.Byte [] -> unit
    member NextDouble : unit -> float
  end

Full name: System.Random
System.Random.NextDouble() : float
val i : int32

  type: int32
  implements: System.IComparable
  implements: System.IFormattable
  implements: System.IConvertible
  implements: System.IComparable<int>
  implements: System.IEquatable<int>
  inherits: System.ValueType
val nth : int -> seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.nth
val printfn : Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

Discriminated unions were used to describe the tennis domain and pattern matching to transition between game score states, e.g. deuce to advantage. Colin Bull came up with a Tennis Monad: http://fssnip.net/8Q.

After lunch the tutorials broke into 2 tracks:

  1. Chris Marinos introduced the F# programming language via his F# Koans
  2. Meanwhile Tomas Petricek showcased Data Access in F#, Today & Tomorrow

 

If you were in the Data Access session you may well have created your own Point of sale application using the Tesco API:

TescoAPI

By the end of the session we’d created our own custom F# 3 Type Provider for .INI files:

IniFileTypeProvider

You can download the source code here.

On the second day in the morning Robert Pickering ran a hands-on session on Building Applications in F# using a WPF Twitter client as the sample. Meanwhile Tomas Petricek and Simon Cousins presented on Asynchronous Programming in F#.

In the afternoon George Stavroulakis & Gian Ntzik ran a very well received session on F# in the cloud, the slides and code for which are available on the M-Brace site.

Unfortunately I couldn’t make their session as I was presenting on TDD & BDD with F#:

The first part of the talk introduced the REPL (F# Interactive) using the code from the Functional Cells: A Spreadsheet in F# article over on the DeveloperFusion site. The tasks for this session are available at: http://trelford.com/progfsharp.zip

Thanks again to all the speakers, attendees, sponsors and Skills Matter for putting on the event.

Please support next year’s Progressive F# Tutorials:

progfsharp2012

Mini Rx: Observable Extensions

The Reactive Extensions (Rx) provide LINQ style querying capabilities for events in C#, VB.Net and JavaScript. Rx implements extension methods over IObservable<T>, just as LINQ to Objects provides a set of extension methods over IEnumerable<T>,

ReactiveExtensions4dotNet

There has been a fair amount of Microsoft publicity on the Rx library in blogs, videos and talks. Demand for Rx skills in IT jobs has grown over the last 12 months. 

Reactive Extensions Demand Trend

That said, the current implementation of the Rx library has at least a couple of issues:

Given that LINQ is based partly on higher-order functions from functional programming perhaps it’s not surprising F# supported querying over events back in 2006. It’s also relatively trivial to expose this functionality to C# by defining compatible extension methods using the ExtensionAttribute e.g.

[<Extension>]
type ObservableExtensions private () =
   [<Extension>]
   static member Select<'T,'U>(source:IObservable<'T>,selector:Func<'T,'U>) =
       source |> Observable.map selector.Invoke
   [<Extension>]
   static member Where<'T>(source:IObservable<'T>,predicate:Func<'T,bool>) =
       source |> Observable.filter predicate.Invoke
   [<Extension>]
   static member Subscribe<'T>(source:IObservable<'T>, action:Action<'T>) =
       source |> Observable.subscribe action.Invoke

This is already enough to provide basic LINQ syntax in C# for types implementing IObservable<T>:

var leftPressedMove =
    from e in mouseMove
    where e.LeftButton == MouseButtonState.Pressed
    select e;

F# custom events implement IObservable<’T> by default and F# provides modules with higher-order functions for both .Net Events and the IObservable<’T> interface.

For C# a mechanism is needed to convert .Net events to an object that implements IObservable<T>. This can be achieved fairly concisely in F# using object expressions:

let FromEvent<'TEventArgs, 'TDelegate when 'TEventArgs:> EventArgs>
    (conversion:Func<Action<'TEventArgs>,'TDelegate>,
        addHandler:Action<'TDelegate>,
            removeHandler:Action<'TDelegate>)  =
    { new IObservable<'TEventArgs> with
        member this.Subscribe(observer:IObserver<_>) =
            let handler = Action<_>(observer.OnNext) |> conversion.Invoke
            addHandler.Invoke handler
            let remove () = removeHandler.Invoke handler
            { new IDisposable with member this.Dispose() = remove () }
    }

Although converting from the event in C# feels a little convoluted:

var mouseMove =
    Observable.FromEvent<MouseEventArgs, MouseEventHandler>(
        f => new MouseEventHandler((sender, args) => f(args)),
        handler => MouseMove += handler,
        handler => MouseMove -= handler);

Again for C# a mechanism is required for directly creating objects that can be both a source of events and be used to observe events. Rx follows the Observer pattern and provides a type called Subject that implements both IObserver<T> and IObservable<T>.

Earlier in the year I put up 2 simple types on F# Snippets, that are functionally equivalent to Rx’s Subject<T> and ReplaySubject<T>:

The ReplaySubject implementation uses F# Agents to simplify concurrency..

The types can be used easily from C#:

var s = new Subject<int>();
s.Subscribe(Console.WriteLine);
s.OnNext(1);

For Silverlight and WPF we need a mechanism for invoking methods on the UI thread, which I implemented in F# back in 2010: Implementing IObservable and extending Observable 

mouseMove
    .Select(e => e.GetPosition(canvas))
    .Delay(closure * 100)
    .OnDispatcher()
    .Subscribe(pos =>
    {
        Canvas.SetLeft(label, pos.X + closure * 10);
        Canvas.SetTop(label, pos.Y);
    });

Putting it altogether, the inevitable "time flies like an arrow" Silverlight demo:


In case you’d like to have a play yourself, I’ve put up a preview release on CodePlex:

http://minirx.codeplex.com/