Monday, 28 May 2007

Threading and Windows Forms

In order to keep a GUI responsive while other computations are being performed, it is essential to combine threading with GUI programming.

On the .NET platform, Windows Forms is the defacto-standard GUI library and it is not thread safe. This means that it is not safe to do anything with a form or any of the form's controls (GUI components) from any thread other than the one that created the form.

This is a serious headache for .NET developers and incorrect multithreaded code is a nightmare to debug.

Fortunately, the F# programming language greatly simplifies the task of adjusting GUIs from other threads. The fundamental concept is the same as the conventional solution on .NET: you create a message loop that queues operations that are to be evaluated on the GUI thread.

A GUI thread, new form and message loop may be created using:

let form = ref null
let make_form() =
form := new Form()
let thread = new Threading.Thread(make_form) in

Note that we have been careful to keep a reference to the form that was created by the new thread.

The form cannot be edited directly from the main thread. However, the form.Invoke() method allows us to queue arbitrary operations for execution on GUI thread and these operations may alter the form at will. Moreover, these operations may be specified as simple functions of the type unit -> unit in F#.

For example, the form may be hidden safely by executing this code on any thread:

form.Invoke(fun () -> form.Visible <- false)

Although this does not make windows forms thread-safe in F#, it does greatly simplify the thread-safe use of windows forms.

Foundations of F#

Robert Pickering is now the author of the first F# book, Foundations of F#. The book is published by APress and they started printing it three days ago. Should hit stores in June!

Congratulations to Robert. Completing a book is an incredible achievement and, having seen the prerelease, I can say that this is a very solid introduction to the F# programming language.

We completed the translation of OCaml for Scientists to F# in February and F# for Scientists should be published by John Wiley & Sons later this year.

Saturday, 19 May 2007

XAML or F#?

XAML is an XML-based scene description language for Windows Presentation Foundation that allows designers to generate graphics and implement GUIs without having to write any code.

Although XAML is a domain specific language, the fact that it is based upon XML makes it quite verbose.

For example, Charles Petzold, author of the book Applications = Code + Markup, recently wrote several blog articles on the use of WPF and XAML, including the following XAML example that rotates four colored squares:

<Page xmlns=""
WindowTitle="Rotating Geometry"
Title="Rotating Geometry">
<RectangleGeometry x:Key="rect" Rect="0 0 100 100">
<RotateTransform x:Name="rotate" />

<Path Canvas.Left="150" Canvas.Top="150"
Data="{StaticResource rect}" Fill="Red" />

<Path Canvas.Left="300" Canvas.Top="150"
Data="{StaticResource rect}" Fill="Blue" />

<Path Canvas.Left="150" Canvas.Top="300"
Data="{StaticResource rect}" Fill="Green" />

<Path Canvas.Left="300" Canvas.Top="300"
Data="{StaticResource rect}" Fill="Yellow" />

<EventTrigger RoutedEvent="Page.Loaded">
From="0" To="360" Duration="0:0:2"
RepeatBehavior="Forever" />

This XAML example can be run directly from his web page.

We thought it would be interesting to translate this example into the F# programming language to see how it compares in terms of functionality and verbosity. Here is the resulting program using the F# for Visualization graphics library:

let square =
[vec3 0. 0. 0., vec3 0. 1. 0., vec3 1. 0. 0.;
vec3 1. 0. 0., vec3 0. 1. 0., vec3 1. 1. 0.] >

let at(c, x, y) =
let aux() = rot_z(time()) * translate(vec3 x y 0.)
dynamic_transform aux square >
color c

let scene =
[Color.Red, -0.75, -0.75;
Color.Blue, 0.75, -0.75;
Color.Green, -0.75, 0.75;
Color.Yellow, 0.75, 0.75] > at > group


In the case of this simple example, the F# programming language can clearly represent the same content more concisely. Moreover, the graphics library provides an interactive 3D interface to the scene with the ability to export to JPEG.

For those designers wanting to generate real-time interactive 2D and 3D graphics who are daring enough to try functional programming, the F# language is a tempting tool. To learn more about the F# programming language, subscribe to the F#.NET Journal today.

Wednesday, 16 May 2007

Particle simulation

Real-time simulation of particle dynamics with a high-performance interactive 3D visualization running in parallel:

3D Surface Plot

Another new demo for our graphics software. This time its a real-time interactive 3D surface plot of a function f(x,z) with only a single line of F# code:

Our library maintains real-time performance even though the tesselation contains tens of thousands of triangles. The visualization can be manipulated with the mouse and exported as an image.

New Icosahedron demo

We just updated F# for Visualization with a new demo:

This one shows off the latest mouse interactivity, export as image and some of the new API in only 6 lines of code.

F# for Visualization

Our F# for Visualization library just went into beta release. This software makes 2D and 3D graphics as easy to use as possible for F# programmers:

Join the beta release scheme now and get the final product free!

Tuesday, 15 May 2007

Who wants F#?

We've been looking at data submitted by readers registering interest in the F#.NET Journal:

The two most popular languages cited are C# and C++. No surprise there, perhaps. The C++ programmers are probably interested in learning something higher-level, with garbage collection and so forth. The C# programmers might be interested in leveraging F# for its integral support for interactivity, built-in numerical types, type inference and (more recently) beautiful support for asynchronous programming.

However, the next most popular language for people wanting to learn F# is Lisp. We found that quite surprising, for one because we didn't realise so many people knew Lisp. These guys are probably yearning for pattern matching, better performance, .NET interoperability and the elimination of run-time errors.

Of the submissions, around half cited performance critical applications as their domain. Compilation to native code is a major benefit here but F# also provides easy interoperability with native-code libraries like LAPACK and FFTW, some superb numerical libraries for .NET like the Extreme Optimization library from Numeric Edge as well as some wierd and wonderful options like compilation of F# to GPU using Accelerator.

Overall, the stage looks set for F# to make a serious impact on the way scientific computing is done, with a bewildering array of exciting projects in all of the major disciplines of science and engineering. Sounds like everyone wants F#.

3D Surface plot in 3 lines of code!

This demo shows a high-resolution 3D surface plot of a function f(x,z) rendered in real time using DirectX with only 3 lines of code:

Monday, 14 May 2007

F# Development using Visual Studio 2005

"The F# distribution includes extensions to Microsoft Visual Studio that provide a rich development environment for F# programmers. In this article, we shall describe how this development environment can be setup and used to make development as easy and productive as possible..."

To read this article and watch its tutorial video, subscribe to the F#.NET Journal today:

Tuesday, 8 May 2007

Structs vs classes

Whilst writing our FFT implementation in both C# and F#:

I noticed several interesting things.

Firstly, C# doesn't provide a type for complex numbers. So you must either pull in a random library or write your own. I think that is a bit of a shame because Microsoft have clearly put a lot of effort into creating a high-performance .NET implementation and lots of people are clearly interested in writing numerical programs in .NET.

Secondly, when you define your own complex number type you have the choice between using a struct and using a class. The difference between the two is essentially that C# will pass a struct by value and a class by reference. The tradition in languages like C++ and C# is to use structs and unbox agressively yourself where possible, with the belief that structs are often faster.

I thought I'd tinker with this because my first F# implementation was 3x slower than my first C# implementation and I remembered that the complex number implementation in the F# standard library still uses a class (structs were only added to F# recently).

Sure enough, reimplementing the complex class in F# with a struct-based version brought the speed up to par, actually slightly faster than the C#.

This was the first of two interesting performance results. The whole program was made 3x faster simply by using a struct rather than a class. Another point for the faith-based view that structs are fast and well suited to atomic values.

Then I tried a similar experiment on our 2D and 3D vector graphics software:

changing the implementation of 2D and 3D vectors to structs. Surprisingly, although I had assumed that low-dimensional vectors have almost identical usage to complex numbers, using a struct is actually ~15% slower. Not a huge performance difference but an interesting result nonetheless.

So structs are not always faster, even for very simple types, and there is no substitute for benchmarking.

I should note that there are more differences between structs and classes in the context of C# because this language exposes more complicated argument passing semantics (value and reference types).

Sunday, 6 May 2007

FFTs again

Noting a distinct lack of decent and cheap FFT implementations for .NET that can be used in commercial products, we recently wrote our own implementations in C# and F#. We've actually made the C# implementation available as a product:

Note the performance results that show a competitor giving quadratic worst-case performance!

Interestingly, the F# implementation is slightly faster than the C#. The style is very similar so the implementations are roughly the same size. F# gives more potential for factoring so I'm probably going to refactor the FFT kernel into something written in a functional style with the aim of exploiting concurrency.

Tuesday, 1 May 2007

The Essence of Functional Programming

Most programmers learning F# will be coming from a background of object-oriented programming languages like C++, Java and C#. For those readers, it is vitally important to forget about object-oriented programming when learning the F# programming language, even though it exposes the OO features of the .NET platform.

F# is fundamentally a functional programming language and the use of functions instead of objects often leads to shorter and clearer code. Indeed, many of the benefits of functional programming are already known to OO programmers in the form of "design patterns".

This article will elucidate the essential properties of functional programming...

To read the rest of this article subscribe to The F#.NET Journal now!