## Sunday, 23 January 2011

### Introduction to Silverlight

The F#.NET Journal just published an article about Silverlight:

"Microsoft's Silverlight allows .NET programs to be run directly in a compliant browser and all major browsers can support Silverlight. This articles describes how self-contained interactive Silverlight programs can be written entirely in the comfort of the F# programming language an easily to deployed to any web server (not necessarily Windows based) as an easy and efficient way to bring dynamic content to a website..."

One of the most popular questions we receive about the old book F# for Scientists is how the gradient descent example can be rewritten to work with the current version of F# in Visual Studio 2010 rather than the early prototype covered in the book, running under Visual Studio 2005.

We begin by referencing the F# PowerPack and its Compatibility extension:

```> #r "FSharp.Powerpack.dll";;
--> Referenced 'C:\Program Files\FSharpPowerPack-2.0.0.0\bin\FSharp.Powerpack.dll'

> #r "FSharp.Powerpack.Compatibility.dll";;
--> Referenced 'C:\Program Files\FSharpPowerPack-2.0.0.0\bin\FSharp.Powerpack.Compatibility.dll'

> #nowarn "62";;```

Next, we define a small number that we be used to calculate numerical approximations to derivatives:

```> let δ = epsilon_float ** (1.0 / 3.0);;
val δ : float = 6.055454452e-06```

The following function repeatedly applies the given function to the given initial value until the result stops changing:

```> let rec fixedPoint f x =
let f_x = f x
if f_x = x then x else fixedPoint f f_x;;
val fixedPoint : ('a -> 'a) -> 'a -> 'a when 'a : equality```

The numerical approximation to the grad of a scalar field is built up from partial derivatives in each direction:

```> let partialD f_xs f (xs : vector) i xi =
xs.[i] <- xi + δ
try (f xs - f_xs) / δ finally
xs.[i] <- xi;;
val partialD : float -> (vector -> float) -> vector -> int -> float -> float```

The following function performs a single iteration of gradient descent by scaling the step size λ by either α or β if the result increases or decreases the function being minimized, respectively:

```> let descend α β f (f': _ -> vector) (λ, xs, f_xs) =
let xs_2 = xs - λ * f' xs
let f_xs_2 = f xs_2
if f_xs_2 >= f_xs then
α * λ, xs, f_xs
else
β * λ, xs_2, f_xs_2;;
val descend :
float ->
float ->
(Vector<float> -> 'a) ->
(Vector<float> -> vector) ->
float * Vector<float> * 'a -> float * Vector<float> * 'a
when 'a : comparison```

Finally, the following function uses the gradient descent algorithm to minimize a given function and derivative:

```> let gradientDescent f f' xs =
let _, xs, _ = fixedPoint (descend 0.5 1.1 f f') (δ, xs, f xs)
xs;;
(Vector<float> -> 'a) ->
(Vector<float> -> vector) -> Vector<float> -> Vector<float>
when 'a : comparison```

For example, the following computes a numerical approximation to the derivative of a function:

```> let grad f xs =
Vector.mapi (partialD (f xs) f xs) xs;;
val grad : (vector -> float) -> vector -> vector```

And the following defines the famous Rosenbrock "banana" function that is notoriously difficult to minimize due to its curvature around the minimum:

```> let rosenbrock (xs: vector) =
let x, y = xs., xs.
pown (1.0 - x) 2 + 100.0 * pown (y - pown x 2) 2;;
val rosenbrock : vector -> float```

The minimum at (1, 1) may be found quickly and easily using the functions defined above as follows:

```> let xs =
vector[0.0; 0.0]
val xs : Vector<float> = vector [|0.9977180571; 0.99543389|]```

For the latest in-depth coverage of the F# programming language, read Visual F# 2010 for Technical Computing.

## Sunday, 16 January 2011

### Testing: Behaviour-Driven Development with F#

The F#.NET Journal just published an article about testing:

"Of the many approaches taken to testing, Behaviour-Driven Development (BDD) is unusual in aiming to provide human-readable tests that can be used by non-technical people. The objective is to write the tests in a high-level language, as close to plain English as possible with data provided in the form of bullet-point lists or tables, that are interpreted by the machine in order to drive a production system and verify its behaviour. Naturally, F# is ideal in this situation because the challenge is essentially to implement an interpreter for a Domain Specific Language (DSL), the task that this family of languages were specifically bred for. This article walks through a complete sample including Gherkin parser, interpreter and harnesses for the NUnit testing framework and F# interactive..."

## Sunday, 9 January 2011

### Simple and efficient hand-written parsers

The F#.NET Journal just published an article about parsing:

"In addition to the powerful code generation tools and libraries that assist with parsing, the ability to write simple and efficient parsers by hand can also be extremely useful. This article examines three different kinds of hand-written parsers ranging from very simple and extensible recursive-descent parsers to highly efficient bottom-up parsers..."

## Monday, 3 January 2011

### Patterns are everywhere!

When people first learn languages from the ML family, like F#, they often mistakenly assume that patterns appear only in match or function expressions. In fact, patterns also appear on the left-hand-side of let-bound definitions. This is why you can write:

`let f(a, b) = a + b`

The pattern is used to destructure a tuple. Specifically, a pair. But this is not just restricted to tuples. You can use that pattern to destructure much more. For example, the following destructures a pair of pairs:

`let f((x1, y1), (x2, y2)) = x1 + x2, y1 + y2`

Things start to get interesting when you pull in some of the more advanced pattern matching features in F#. For example, the following uses an or-pattern to select the value x is bound to depending upon the structure of the input:

`let def (_, Some x | x, None) = x`

This function takes a pair of values. The second value is of an option type. If that second value has the structure Some then its argument is the return value of the def function. Otherwise, the structure is None and the first argument is returned. Therefore, this def function mimics the behaviour of the built-in defaultArg function, returning the value conveyed by an optional type (if any) or a given default value otherwise.

Pattern matching is one of the enormously powerful features offered by the F# programming language. This feature and more are described in my new book Visual F# 2010 for Technical Computing.