Phillip Trelford's Array

POKE 36879,255

Turtle Graphics

Over time I’ve been trying to engage my young children with computer programming, so far we’ve looked at Squeak, Small Basic and more recently F#.

They really enjoyed playing with the Turtle in Small Basic, an idea that comes from Logo, a programming language I myself played with as a child.

For i = 1 to 4
  Turtle.Move(100)
  Turtle.TurnRight()
EndFor

Small Basic is a variant of Basic with just 14 keywords. It also ships with a library of static methods for fun stuff like graphics and sound, removing the need to understand the vagaries of threading before getting started.

The SmallBasicLibrary.dll can be also be referenced from C# and F#. However, rather than using value types for passing parameters, it defines it’s own union type called Primitive and associated implicit conversions, a little like the Variant type used in Visual Basic.

I’ve been trying a few different ways of bringing first class Turtle graphics to F#. A few months back I created a simple internal DSL in F# that looks quite a lot like Logo, and can be run in the browser:

repeat 10 [rt 36; repeat 5 [fd 54; rt 72]]
|> Turtle.Run

Just hit the TryFSharp.org button on this Turtle F# Snippet, or download the Silverlight code.

TurtleInternalDSL

More recently based on some of the ideas in the Small Basic Library, I’ve created a small library for C# and F# called Small Sharp, which is hosted on CodePlex.

using Library;

class Program
{
    static void Main(string[] args)
    {
        GraphicsWindow.Show();      
        Turtle.PenName("Red");
        (1000).Times(i =>
        {
            Turtle.Forward(6);
            Turtle.Right(i * 7);
        });
    }
}

Small Sharp provides a fun environment to learn about programming, while giving you the full power of either the C# or F# programming languages. It also includes some LINQ and Ruby like extension methods, for example the sample above runs 1000 times.

TurtleCSharp

Instructions for getting started with C# and F#

DDD Belfast 2011

This weekend I flew into Belfast for their Developer Developer Developer (DDD)  conference. The DDD conferences are run by the developer community for the developer community, where sessions are voted on prior to the conference. I highly recommend these free events, there always seems to be a great range of interesting talks, not to mention plenty of lively discussion between sessions. The next event is DDD North next weekend, Saturday 8th October, in Sunderland.

Interestingly there were enough F# sessions at DDD Belfast to have a dedicated track (3), which is where I spent most of the day.

My first talk of the morning was F# Eye 4 the C# Guy (a title I ahem, recycled, from an excellent talk by Leon Bambrick given 3 years ago):

Next up was Tomas Petricek on Asynchronous Programming in F# and C#. If you’re in London, Tomas is repeating this talk at Skills Matter this Wednesday (5th October), register free here: http://www.meetup.com/fsharpLondon/

Shipping in VS11, C# 5’s Async (await) support will be very similar in implementation to C# 2’s Iterators (yield). They are both basically implementations of coroutines.

F#’s Async Workflows are available now in VS2010.

Before lunch I was up again to talk about Behavioural Driven Development (BDD) with F#:

After lunch Adam Granicz presented Developing F# Applications with WebSharper on track 3. I popped over to see Richard Dalton’s great information packed session Aha! Unit Testing.

Slides and samples: http://www.devjoy.com/2011/10/aha-unit-tests-dddbelfast/

Richard gave some really interesting observations, for example unit tests are “An Extra Client” (slide 5), and therefore it is OK to add artefacts in your code to support them. The talk presented a number of Aha! moments:

Unit Testing - Excutes Unit Testing - Real Reason

 

There were also some good tips on Mocks and Stubs (Stubs are Stooges, Mocks are Spies), including some code examples using TypeMock and references to Microsoft Research’s Moles project and Martin Fowler’s Mocks Aren’t Stubs article.

Track 3 ended with a lively Panel Discussion, which covered a variety of subjects from BDD, Concurrent programming with Agents, Parsers, Units of Measure through to games development.

Thanks again to all the attendees, sponsors, speakers and particularly Jackie Pollock for organizing the event.

Pattern Matching Database Records

Last week Jon Harrop showed me some interesting data access code (Jon and I often share the same Cambridge to London train). The code used pattern matching to match records returned from a SQL command, for example.:

let values = [for index in 0..reader.FieldCount-1 -> reader.GetValue index]
match values with
| [Date date; Price o; Price h; Price l; Price c] -> 
    yield date, o, h, l, c
| _ -> invalidOp "Record mismatch"

The code fragment above matches open-high-low-close (OHLC) field values read from an IDataReader. The first line creates a list of field values; these values are then matched using a List pattern with Active Patterns to unbox the objects to strongly typed values, i.e:

let (|Date|) (value:obj) : DateTime = unbox value
let (|Price|) (value:obj) : float = unbox value

Instead of constructing a list each time a pre-allocated array can be employed using the IDataRecord.GetValues method and an Array pattern:

seq {
    let values = Array.zeroCreate reader.FieldCount
    while reader.Read() do       
        reader.GetValues values |> ignore
        match values with
        | [|Date date; Price o; Price h; Price l; Price c|] -> 
            yield date, o, h, l, c
        | _ -> invalidOp "Record mismatch"
}

 

The OHLC values are returned as a tuple from inside a sequence expression which is the equivalent of a C# iterator block.

Pattern Matching

I think this is another great example of the power of pattern matching, a feature common to functional programming languages. Somewhat strangely it’s a feature missing from older and more established object-orientated languages like C++, C# and Java. However there is nothing intrinsically stopping these OO languages from supporting pattern matching. Pattern matching has been successfully implemented in newer moustache/curly-brace based languages like Scala, Nemerle and Kotlin. Progress in Java seems to be severely hampered by committees, just look at how long it took to get to Java 7. C# seems to be making more progress but I think may in part be hampered by the compiler being implemented in C++, which Project Roslyn may fix in the future.

Ordinals

The pattern matching approach makes use of the order of the fields. Another approach employed in examples in both Jon’s F# for Scientists and Don’s Expert F# book, is to get the field values based on their ordinals, i.e.:

yield 
    reader.GetDateTime(0), 
    reader.GetDouble(1),
    reader.GetDouble(2),
    reader.GetDouble(3),
    reader.GetDouble(4) 

String Literals

Yet another approach, used as an example in Professional F# 2.0, is to use the field names:

yield 
    reader.["Date"]  :?> DateTime,
    reader.["Open"]  :?> float,
    reader.["High"]  :?> float,
    reader.["Low"]   :?> float,
    reader.["Close"] :?> float

Dynamic Lookup

And now for a one line ORM which simply overloads F#’s dynamic lookup operator:

let (?) (reader:IDataReader) (name:string) = unbox reader.[name]

This really helps reduce the boilerplate:

yield 
    reader?Date, 
    reader?Open, 
    reader?High, 
    reader?Low, 
    reader?Close

For more information on this approach see Tomas Petricek’s excellent post:

Plotting

Now we’ve explored 5 different ways of doing exactly the same thing it’s probably time to do something useful like plotting.

Again Tomas has a tutorial for that:

Plotting a chart from inside F# interactive using Carl Nolan’s new FSharpChart library:

#load "FSharpChart.fsx"
open MSDN.FSharp.Charting

[ for date,o,h,l,c in getHistoricalPrices "MSFT" -> date, (h,l,o,c) ]
|> List.filter (fun (date, _) -> date >= DateTime(2011,08,01))
|> FSharpChart.Candlestick

Gives us a Candlestick chart for MSFT stock since August:

MSFT

Final Thought

With Type Providers in F# 3 a lot of complexity will disappear, as we get type safe data access with intellisense (rather than strings or ordinals) without the need for code generation!