Granville Barnett

September 2007 - Posts

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.

Recursion in F#

When talking about recursion the example that everyone thinks of is the fibonacci numbers, get a book on algorithms and you can almost bet your house that that algorithm is there.

First off, just like C# and all other languages if you don't have a case(s) that your recursive case gets ever closer to in the recursive case then you are going to eventually just smash the stack to bits resulting in some overflow exception - F# just like C# and any other managed language will eventually throw a StackOverflowException.

Here is a bad fibonacci algorithm (you'll probably never see this anywhere - it's that bad!).  This algorithm only has a recursive case, the fib function is going to call itself forever resulting in a StackOverflowException.

let rec fib n = 
match n with
| n -> fib (n - 1) + fib (n - 2)

I'm not quite sure if the above example is at all relevant, the point I'm trying to make is that all functional languages use recursion immensely when processing any form of data so it's important to remember the basics of recursion:

  • Base case(s) (usually the very easy bits that you can do quite quickly)
  • Recursive case (the harder bit, this should ultimately call your base case(s))

With that in mind here is the correct fibonacci algorithm.

let rec fib n = 
match n with
| 1 -> 1
| 2 -> 1
| n -> fib (n - 1) + fib (n - 2)

This example isn't exclusive to F#, you can go ahead and replicate this in C# or C/C++ very easily.  Here is the C++ example (and yes, I know I'm assuming the input is positive - this should work for C# also).

int Fib(int n) { 
if (n < 3) return 1;
return Fib(n-1) + Fib(n-2);
}

The recursive implementation of fibonacci is very expensive, pass in a fairly large number and you witness the expense of recursion in this case, draw out a recursive tree for the number 9 and you will see something that's pretty big - and 9 is pretty small.

There is a case where by 0 returns 0, I've omitted that.  The maths function definition for fibonacci is here.

Posted: Sep 23 2007, 04:02 PM by gbarnett
Filed under: ,
MSIL the language of the CLR (Part 1)

I got asked to do something on Channel 8 about MSIL so here is the first part.

Posted: Sep 22 2007, 11:35 AM by gbarnett | with 1 comment(s)
Filed under: , ,
C++ exceptions

Another great video on C++ by Ale Contenti on Channel 9 on exceptions.  Required viewing.

The C++ team videos are by far the best on C9...by far!

Posted: Sep 21 2007, 05:38 PM by gbarnett
Filed under:
Functions as values in F#

One of the things I love about functions in functional languages like F# and Haskell is that they are treated like values. 

#light

let multiply a b = a * b

The multiply function has the signature Int -> Int -> Int where int is Int32.  In Haskell you would explicitly define the signature of the function, but you don't in F#.

If you run the below example first in F# interactive you will see the signature of the function changing until all of its function parameters have been satisfied.

#light

let multiply a b = a * b
let m1 = multiply 3 
let m2 = m1 3

values1

You can see that m1 is a function that expects a single int argument, and m2 simply holds the result of the multiply function.

  1. We define a function multiply which expects 2 int arguments and returns an int.
  2. the value of m1 is a function that expects a single argument as we have already provided one of the two arguments required by the multiply function.
  3. The value of m2 is simply a single integer (9) as we have invoked the function m1 (int -> int) passing in the missing argument 3.

If you print out the value of m2 you will see 9.

Posted: Sep 19 2007, 05:55 PM by gbarnett
Filed under:
Using F# interactive

Just a quick post on how to get the best out of F# Interactive

What is F# interactive?

That's a dang good question!  Well you can think of F# interactive as being a console application that you type stuff into and its evaluated and based on what you type in the response varies - you may get something back saying "hey you just defined something of type int", or maybe something that is a function call, and here is it's returned data as a result of running that function.

Although not the same if you have used Hugs then you will be pretty well suited for F# interactive.

How do I get it?

Install the latest build of the F# compiler from the MSR site here, the installer will go ahead and install a Visual Studio add-in.  The add-in is basically a window that you can activate within VS by going to Tools -> Add-In Manager, then from there selecting F# Interactive.

addin

Single screen?  Dual screen?

You can use the window within VS as something you choose to appear or disappear - which is ok but if like me you like code space to maximized then this can be a little restricting.

interactive

Instead I drag this window out onto my 2nd monitor so it's always visible - obviously if you don't have a 2nd monitor this is no use to you but if you do then you will learn to love it!

Actually using F# interactive 

So, we've talked about it now lets use it!  Go ahead an write some F# statement and then select the statement(s) that you want to execute and then hit Ctrl+Return and F# interactive will register your input via some textual feedback, e.g.

#light

open System

let x = 6
Console.WriteLine(x)

If you select each line of the code above then hit Ctrl+Return then you will see the following output:

fsdemo

I'm not going to run into this now, but you can see that the type of x is inferred from its value to be an int, and then the method call to System.Console.WriteLine(...).

Do you expect me to make my users run my F# code like this?

No.  F# interactive is primarily a learning and experimentation aid - if you want to deploy something in an application then do so as some managed assembly.  Using F# interactive allows you to step through the execution of code which is very useful.

Posted: Sep 19 2007, 05:51 PM by gbarnett | with 1 comment(s)
Filed under: , ,
How to register the F# project with VS 2008 Beta 2

In this post I mentioned that F# compiler doesn't register its project correctly with VS 2008 Beta 2.

Repo:  Clean installation of Vista, with no previous .NET 3.5 or VS 2008 Beta bits installed.  Subsequent installation of the F# compiler installs but VS F# project is not registered with VS.

Here is what you need to do:

  1. Edit the alternative-install-vs2005 bat file to target the new location of VS 2008 right at the end of the file.
  2. Run alternative-install-vs2005 as admin elevated privs.

That should be all you need to do.

I actually fixed this a while ago now but thanks to Tomas Petricek for his help nonetheless.

Posted: Sep 19 2007, 05:46 PM by gbarnett | with 3 comment(s)
Filed under: ,
Expression Tree Visualizer

I played with this a while back but never blogged about it and thought that maybe I should do now as its a pretty nifty tool.

First and foremost, if you have not looked at C# 3.0 or LINQ then here are some articles that I have written on the subject:

Expression tree's are a nice feature in C# 3.0 and like many things in Visual Studio there are things called visualizers which allow you to look at things in a clearer light - the same is applicable for Expression tree's.

Note:  in order to get this visualizer you need to go to the samples folder where you installed VS and open the visualizer project and build it then copy it to the visualizer folder in Documents and Settings for your user.

With the visualizer installed add a breakpoint and then hover over the expression and click the magnifying glass, now you get the following view of your expression tree:

visualizer

Hopefully this will be the default come Visual Studio 2008 RTM.

Posted: Sep 15 2007, 08:08 PM by gbarnett | with 6 comment(s)
Filed under: , ,
DSA 0.2 released

The 0.2 release of DSA has just been released, features for this release include:

  • ArrayListCollection(Of T)
  • DoublyLinkedListCollection(Of T)
  • SinglyLinkedListCollection(Of T)
  • StackCollection(Of T)
  • QueueCollection(Of T)

There are also a few algorithms that make there debut (very simple ones - time was consumed with the data structures):

  • Reverse
  • Any

More algorithms will be in the 0.2.1 release which is a minor release, probably with some bug fixes also :-)

All data structures are meant to be interacted with exactly (almost!) like those in the BCL, so if you find that something doesn't act the same was as the BCL equivalent then please tell me.

Download DSA 0.2.

Run FxCop on your code it costs nothing!

I've seen quite a bit of code written by others recently, for various reasons but the one thing that they all have in common is miserable results when running FxCop (Code Analysis).

Running FxCop is a great way to gain consistency through guidelines that have been well established by both Microsoft and it's customers.  I'm sorry people but there is just no excuse for not using this tool, it's free for a start!  And second it consumes only a few seconds of your life.

For those that are reading this and thinking "what is FxCop?" put simply it's a static analysis tool for your code (managed code that is).

I'm not sure if it will get migrated to CodePlex, for now it's still on GotDotNet.

If you are not going to take my word for why you should use it, fine, but I should tell you that FxCop won the Chairman's Award for Engineering Excellence at Microsoft - really it's that good!  Nice to see Dr Watson on there too :-)

Brad Abrams talks more about the award and FxCop here.

In short please run FxCop on code libraries you are developing, you will really benefit from it's guidance.

Note: and yes the number of times I have linked to the FxCop project page was intentional!

More Posts Next page »