Granville Barnett

Reference assemblies the clean way in F#, not the ugly way

I've seen quite a lot of F# code recently (well, as much F# as is on the Internet) that references assemblies in a very ugly way.

Just because it's F# code there is no reason not to test the code in your application, so we will use testing as the basis of the example, and assume that we are using NUnit as the testing framework.

First the ugly way to reference Nunit.Framework.dll:

#light

#r @"C:\Program Files (x86)\NUnit 2.4.3\bin\nunit.framework.dll";;

open NUnit.Framework

// ... 

Now the "cleaner" way that uses a build command to reference an external assembly, in this case I'm actually copying the assembly to my local working directory as well.

fr1

Now you can go ahead and rid your source code files of pre compilation directives.

#light

open NUnit.Framework

/// algorithm to computer factorial of an integer n
let rec fact n =
    match n with
    | 1 -> 1
    | n -> n * fact (n - 1)

[<TestFixture>]
type NumbersTest = class
    new() = {}
    
    [<Test>]
    member x.FactTest() =
        Assert.AreEqual(1, fact 1)
        
    [<Test>]
    member x.FactTest2() =
        Assert.AreEqual(120, fact 5)
        
    [<Test>]
    member x.FactTest3() = 
        Assert.AreEqual(24, fact 4)
end

There are a few other flags that you can also use including -r which will reference an assembly but not copy it locally, as well as -I which allows you to set a common path to look for assemblies so you can use shorter path qualifiers when referencing assemblies - useful when you are referencing multiple assemblies in a particular directory.

Comments

No Comments