Saturday, October 18, 2008

Breaking Down The Code

Overview:

Last week we walked through creating our first F# application using TDD (Test Driven Development). Today we will break down that first example to identify what each of our commands are doing.

Here's a review of the extremely simple application that we wrote:

Test:
[TestMethod]
public void CanCalculateNumberSquared()
{
int result = FSharpSample.CalculateNumberSquared(2);
Assert.AreEqual(result, 4);
}

Code:

#light
let CalculateNumberSquared x = x*x;;

Breaking Down The Code:

So what does this all mean?

#light
The #light (pronounced "Hash" light) compiler directive provides various features that simplify the F# language. It also allows compatibility with the language OCaml. At the time of this writing, most experts recommend the use of this directive.

Identifiers:
The "let" keyword allows the programmer to associate any value or formulate to an "Identifier". Here's how Robert Pickering describes identifiers in his book "Foundations of F#". "To most people coming from an imperative programming background, this will look like a variable assignment. There are a lot of similarities, but there are key differences. In pure functional programming, once a value is assigned to an identifier, it never changes. This is why I will refer to them throughout this book as identifiers and not variables." If you have not read this book, I strongly recommend it.

In our example, we are setting up an identifier named "CalculateNumberSquared", specifying a parameter named "x", and finally providing instructions on what to do with that parameter. This identifier can then be passed around to other identifiers and/or functions.

This ability to pass around functions and identifiers is one of the great features in F#. While it may take some time to get use to this concept, you will soon wonder how you ever got along without it.

No comments:

Post a Comment