Thursday, April 22, 2010

The bug that never happened.

I was demonstrating some F# code in Visual Studio 2010. It is shown below and it defines and then computes the discriminant function for quadratics.

let quadratic = fun a b c -> (b * b) - (4 * a *c)
let discriminant = quadratic 4 5 6
printfn "discriminant = %d" discriminant

Everything works, no surprise. But then as I modified the code. In particular as I changed the last line to:

printfn "discriminant = %d %d" discriminant

A compile warning occurred! So the compiler parsed the formatting string as well and checked that there where enough parameters provided. No doubt there is a nuance to functional programming that is requiring this level of checking.

But compare this to a line of C#

string wrongNumberOfArgs = string.Format("{0} {1}", 12);

The c# compiler is perfectly okay with this and it is only at runtime that you get the crash. In the simple case that I have shown this does not matter. But simple cases are not where this occurs. It is when it is complex that it occurs. So in the C# case you will find this out when you execute the code, when your mind has switched contexts.

In the F# case, the compiler warning is immediate because of the incremental compiles. You are best positioned to fix the code because you just keyed it in. In fact this is a bug that never happened.

No comments: