Category Archives: F#

Changing a value within an XML document using F#

I needed to simulate some user interaction with our webservices in an automated manner. This post is specific to one small part of this requirement – here we’re going to simply take some XML and change a value within the data and return this altered data.

The code is very simple but demonstrates how to deal with namespaces as well as using XmlDocument and XPath.

Note: I’m using XmlDocument here and XPath for simplicity but obviously this is not the most performant on large documents.

Mutual recursion in F#

One of the annoyances of F#, well it is when you come from C# (or the likes), is that to use a function or type, the function or type needs to have been declared before it’s used. Obviously this is a problem if a type references another type which itself references the first type – but ofcourse they F# guys have a way to handle this and it’s called mutual type recursion.

Let’s look at an example of what I’m talking about and at the solution

[<Measure>
type g = 
   static member toKilograms value : float<g> = value / 1000.0<g/kg>
and [<Measure> kg = 
   static member toGrams value : float<kg> = value * 1000.0<g/kg>

The above is taken from my previous post on units of measure.

So in the above code we have type g returning a unit of measure type kg and type kg returns a unit of measure type g. Obviously g cannot use kg as it’s not declared before type g, but it can in the above example by using the and keyword. This can be thought of, as telling the compiler to wait until it’s read all the “chained” types in before evaluating them.

The same technique is used for creating recursive functions which might call other functions which might call the previous function, i.e. circular function calls.

Here’s some code taken from Microsoft’s MSDN site (referenced below) as this is a better example than any I’ve come up with to demonstrate this

let rec Even x =
   if x = 0 then true 
   else Odd (x - 1)
and Odd x =
   if x = 1 then true 
   else Even (x - 1)

So in this code we can see that the function Even is marked as rec so it’s recursive, it may call the function Odd which in turn may call function Even. Again we chain these functions together using the and keyword.

References

Mutually Recursive Functions
Mutually Recursive Types

More Units of Measure

In a previous post I looked at the unit of measure feature of F#. Now it’s time to revisit the topic.

So as a refresher, we can define a unit of measure in the following manner

[<Measure>]
type kg

and we use the unit of measure thus

let weight = 75<kg>

Now it’s important to note that the unit of measure feature only exists at compile time. At runtime there’s no concept of the unit of measure, i.e. we cannot use reflection or anything else to see what the unit used was as it no longer exists. However at compile time the code will not build if we try and use a value with a unit of measure on which is not compatible with another unit of measure.

But there’s more we can do with a unit of measure which makes them even more useful. We can supply a unit of measure with static member functions, for example

[<Measure>
type g = 
   static member toKilograms value : float<g> = value / 1000.0<g/kg>
and [<Measure> kg = 
   static member toGrams value : float<kg> = value * 1000.0<g/kg>

In the example above we use a mutually recursive type (using the and syntax). This allows the g type to use the kg type and vice versa.

With this code we can now write

let kilograms = g.toKilograms 123<g>

The result of this will assign the value kilograms with the result of the toKilograms function as well as setting it’s unit of measure to kg.

Whilst assigning a unit of measure to a numerical value is simple enough, to apply it to an existing value requires the use of an F# core function, from the LanguagePrimitives module.

This code creates a value with a unit of measure

[<Measure>] 
type g = 
    static member create(value : float) = LanguagePrimitives.FloatWithMeasure<g> value

So in the above code we might pass in a value and using the FloatWithMeasure function we apply the g unit of measure

let weight = 123
let weightInGrams = g.create weight

The weightInGrams value will now have the g unit of measure applied to it.

Randomly generating test data using FsCheck

My latest small project is to write a bunch of conversion functions in F#. Basically I want to convert things like, weights from kg to stones. Metres to feet and so on.

I wrote a couple of tests to ensure that the conversions were as expected, but ofcourse with such a set of functions and the wide range of values one might pass to them, my tests simply confirmed a couple of values were correct. It’d be nice to feel like I could say this function is valid for all values within the range x to y.

This is where FsCheck can help.

To use FsCheck just use nuget and search for FsCheck, I also use XUnit so chose FsCheck with XUnit support.

With FsCheck we create properties which define a valid state for a test, so for example if I have a function toMillimetres and another toKilometres, then we can expect that for every value entered into toMillimetres the function toKilometres will return the original value.

This can therefore be described as a property.

At this point we also need to beware that if the calculations involve floating point numbers we may not get back exactly the value we entered, so we’d use something like FsUnit to add a “tolerance” to the formula, i.e. it’s within 0.1 of the expected answer.

Let’s look at some code

[<Property>]
let ``From kilometre to millimetre and back`` () =
   let property value = 
      let millimetres = km.toMillimetres (km.create value)
      let kilometres = mm.toKilometres millimetres

      kilometres
      |> should (equalWithin 0.1) value

   Check.QuickThrowOnFailure (testRange property)

So I’ve created an FsCheck property test named From kilometre to millimetre and back the idea being that (as previously stated) we can put a value into the toMillimetres function then put the result into the toKilometres function and expect (within a tolerance of 0.1) the value to be the same as the resultant kilometres.

The function Check.QuickThrowOnFailure takes our property and in this case, because I wanted to limit the range of the testing, the property goes through the function testRange (which is nothing very exciting) but I’ve listed it below for completeness

let testRange f value =
   let inRange v = (v > -1E+10) && (v < 1E+10)
   inRange value ==> lazy (f value)

The above code simple takes a function f (the property function from the test) and is supplied a value via FsCheck. We then simply ensure the value is within the range -1E+10 to 1E+10 by calling the inRange inner function.

Now when we run this property via FsCheck it will pass multiple values into the property function within the range we’ve defined and runs the unit test.

Note: In the property code I’m using FsCheck with XUnit and FsUnit with Xunit.

F# Array Slicing

This should be a short post regarding something I hadn’t seen before – F#’s array slicing syntax. One of the problems of coming to F# from another language is that sometimes you just use language features without realising that the new language offers more options – this is one such feature of arrays in F#.

An array slice is really just a way of creating an array made up of a subset of another array. So for example let’s assume we have the following

let array = [| 1; 2; 3; 4; 5; 6 |]

We can access the array via an indexer, but as you probably know, you access the indexer using dot notation, for example

let v = array.[3]

But we can do more than just get a single item, we use the same basic syntax to get slices of the array, for example

// create a new array of items 2 to 4 inclusive
let a = array.[2..4]

// create a new array of items up to and including item 3 (i.e. 0..3)
let b = array.[..3]

// create a new array of items from item 3 until the end of the array
let c = array.[3..]

// create a clone of all elements
let d = array.[*]

Active Patterns in F#

Active patterns have been causing me a few headaches, trying to understand the syntax. Let’s take a look at how we might declare an active pattern.

Note: I will be using the sample from Active Patterns (F#)

So, this is the syntax for declaring an active pattern. The Microsoft documentation states the (| .. |) brackets are known as banana clips. So we declare the types within the banana clips and separated by the | operator, such as

let (|Even|Odd|) input = if input % 2 = 0 then Even else Odd

So you’ll notice that the syntax does not include a function name, but only declares the type that the code can be matched against. Here’s an example of using this code within a pattern match

let test input =
   match input with
   | Even -> printfn "%d is even" input
   | Odd -> printfn "%d is odd" input

Now what happens is – when the function test is called with an input, for example

test 2     // this will output 2 is even

The line below the match tells F# to find the code which matches against a type Even or type Odd and run it. So in this case it will output 2 is even if we had executed the same code with the int 3 Odd would be returned from the active pattern and obvious 3 is odd will be output.

An extremely useful post on how the code can be viewed is on F Sharp Programming/Active Patterns.

To save time I’ll recreate the code here – so the declaration for the active patterns can be viewed as

type oddOrEven =
    | Even
    | Odd
 
let getChoice input = if input % 2 = 0 then Even else Odd

Function overloading in F#

F# doesn’t support function overloads, so you cannot write the following

let add a b = a + b
let add a b c = a  b + c

However one thing we could do is implement a discriminated union, for example

type Addition =
    | Two of int * int
    | Three of int * int * int

let add param =
    match param with
    | Two (a, b) -> a + b
    | Three (a, b, c) -> a + b + c

Now to call the function using this code we’d write

let a = add <| Three(1, 2, 3)

// or

let a = add (Three(1, 2, 3))

in C# we would use

var a = Dsl.add(Dsl.Addition.NewThree(1, 2, 3));

Query expressions in F#

Not quite the same as LINQ in syntax terms, F# includes query expressions which are in essence it’s own style of LINQ.

If we assume we have a simple example of some code in C# which uses LINQ to get strings from an array where their length is 3. In C# this might look like the following

string[] sample = {"One", "Two", "Three", "Four", "Five"};

IEnumerable<string> result = 
   from s in sample 
   where s.Length == 3 
   select s;

Note: I’ve purposefully put each part of the LINQ query on a new line for easier comparison with the equivalent F# query expression.

So here’s the same in F#

let sample = [| "One" ; "Two" ; "Three" ; "Four" ; "Five" |]

let result = query {
   for s in sample do
   where (s.Length = 3)
   select s
}

The main differences are the use of the query expression syntax query { … } and the use of the for s in sample do instead of from s in sample

References

See Query Expressions (F#) for a few examples of different query expressions and how they relate to SQL queries (and more).

Type extensions in F#

We can extend F# types by adding the equivalent of C# extension methods or something similar to partial classes in C#.

Let’s not waste time but instead get straight into the code

The type extension syntax is taken from Type Extensions (F#) which is well worth a read

type typename with
   member self-identifier.member-name =
      body
   ...
   [ end ]

[ end ] is optional in lightweight syntax.

Here’s an example of a type method for the System.String type, we’re going to add a simple Reverse function

type System.String with
    member __.Reverse = String(__.ToCharArray() |> Array.rev)

also we can create new functions like adding to a partial class

type System.String with
    member __.Append s = __.Substring(0) + s

A slightly pointless method, but at the time of writing I couldn’t think of anything more interesting.

Creating an F# WinForms application

I wanted to mess around with the FSharp.Charting library and needed to create an F# WinForms application to use it.

It’s pretty simple but there’s no template by default in Visual Studio (well not in 2013).

So here the steps to create a WinForms F# application

  • Create a new Project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add a reference to System.Windows.Forms
  • Change your main function to look like the following
    open System
    open System.Windows.Forms
    
    [<EntryPoint>]
    [<STAThread>]
    let main argv = 
    
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault false
    
        use form = new Form()
    
        Application.Run(form);
    
        0 
    

Obviously this example shows us creating an empty Form. By default F# (at least in Visual Studio 2013) doesn’t include WinForm design surfaces or the likes. So it’s probably best to design your forms in a C# library and reference from your F# applications. Or, alternatively, you can hand code your WinForms.

A quick example of using FSharp.Charting

This is not mean’t to be anything other than a quick example, but as I wanted to get a F# WinForms application specifically to try out some FSharp.Charting, here’s the steps…

  • Using NuGet add a reference to FSharp.Charting to your project (developed above)
  • Add open FSharp.Charting to your Program.fs file
  • I’m going to simple use some code from the FSharp.Charting github samples, so first we need to add a reference to System.Drawing
  • Add a reference to System.Windows.Forms.DataVisualization
  • Finally change the Application.Run method to look like the following
    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())
    

Now your code should look like the following

open System
open System.Windows.Forms
open FSharp.Charting

[<EntryPoint>]
[<STAThread>]
let main argv = 

    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault false

    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())

    0

and this should (when run) display a line chart.