Learning F# – Part 1

I decid­ed to take some time out on Sil­verlight and have a play around with Microsoft’s new lan­guage F#, I’ll be mak­ing notes as I go along and post them here so maybe they’d help sat­is­fy some of your curios­i­ty too!

Dis­claimer: I do not claim cred­it for the code exam­ples and much of the con­tents here, these are most­ly extracts from the book by Chris Smith, Pro­gram­ming F#: A com­pre­hen­sive guide for writ­ing sim­ple code to solve com­plex prob­lems. In fact, if you’re think­ing of learn­ing F# and like what you read here, you should buy the book your­self, it’s easy to read and the author has gone go great lengths to keep things sim­ple and includ­ed a lot of code exam­ples for you to try out your­self.

Before you start, you need to down­load F# from:

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/release.aspx

and install it for either VS2008 or VS2010 beta.

Hello, World

In VS2008, open a new project and choose F# Appli­ca­tion, in Program.fs type in:

printfn “Hel­lo, World”

Hit Ctrl+F5, and voila:

You might notice that your pro­gram worked with­out an explic­it Main method.

Here’s a slight­ly more com­plex Hel­lo, World to show off the syn­tax of F#:

image

The let key­word binds a name to a val­ue, unlike most oth­er pro­gram­ming lan­guages, in F#, val­ues are immutable by default (mean­ing they can­not be changed once ini­tial­ized).

image

F# is also case-sen­si­tive. The name of a vari­able can con­tain let­ters, num­bers, under­score, or apos­tro­phe (‘) and must begin with a let­ter or an under­score. How­ev­er, you can enclose the value’s name with a pair of tick­marks in which case the name can con­tain any char­ac­ter except for tabs and new­line:

let “this.Isn’t %A% good val­ue Name$!#“ = DateTime.Now.ToString(“hh:mm tt”)

printfn “%s, %s at %s” greet­ing thing “this.Isn’t %A% good val­ue Name$!#“

Oth­er lan­guages like C# use semi­colons and curly braces to indi­cate when state­ments and blocks of code are com­plete, but it clut­ters the code.

In F#, white­space (spaces and new­lines) is sig­nif­i­cant. The F# com­pil­er allows you to use white­space to delim­it code blocks. For exam­ple, any­thing indent­ed more than the if key­word is con­sid­ered to be in the body of the if state­ment. Because tab char­ac­ters can indi­cate an unknown num­ber of space char­ac­ters, they are pro­hib­it­ed in F# code. You can con­fig­ure the Visu­al Stu­dio edi­tor to auto­mat­i­cal­ly con­vert tab char­ac­ters into spaces in Tools -> Options -> Text Edi­tor -> F#.

The ear­li­er code also demon­strat­ed how F# can inter­op­er­ate with exist­ing .Net libraries:

let time­Of­Day = DateTime.Now.ToString(“hh:mm tt”)

F# can take advan­tage of any .Net library by call­ing direct­ly into it, con­verse­ly any code writ­ten in F# can be con­sumed by oth­er .Net lan­guages.

Comments

Like any lan­guage, F# allows you to com­ment your code. To declare a sin­gle line com­ment, use two slash­es (//).

For larg­er com­ments that span mul­ti­ple lines, you can use the mul­ti­line com­ments using (* and *) char­ac­ters.

For F# appli­ca­tions writ­ten in Visu­al Stu­dio, there is a third type of com­ments: an XML doc­u­men­ta­tion com­ment. If a com­ment start­ing with three slash­es (///) is placed above an iden­ti­fi­er, Visu­al Stu­dio will dis­play the comment’s text when you hov­er over it:

 


F# Interactive

Visu­al Stu­dio comes with a tool called F# Inter­ac­tive or FSI. F# Inter­ac­tive is a tool known as a REPL (read-eval­u­ate-print loop), it accepts F# code, com­piles and exe­cutes it, then prints the results. This allows you to quick­ly and eas­i­ly exper­i­ment with F# code sim­i­lar to how snip­pet edi­tor allows you to do the same with C# code.

Once it’s open, it accepts F# code until you ter­mi­nate the input with ;; and a new­line, the code entered will be com­piled and exe­cut­ed. After each code snip­pet is sent to FSI, for every name intro­duced you will see val <name> : type val­ue, for exam­ple:

Notice when you don’t give a vari­able a name, FSI will sim­ply call it ‘it’.

FSI allows you to write code in Visu­al Stu­dio edi­tor which offers syn­tax high­light­ing and Intel­liSense, but test your code in the FSI win­dow. You can copy the entire code body from the exam­ple ear­li­er and test the main method in FSI by call­ing it:

Managing F# Source Files

The F# lan­guage has some unique char­ac­ter­is­tics when it comes to man­ag­ing projects with mul­ti­ple source files. In F#, the order in which code files are com­piled is sig­nif­i­cant.

You can only call into func­tions and class­es defined ear­li­er in the code file or in a sep­a­rate code file com­piled before the file where the func­tion or class is used. If you rearrange the order of the source files, your pro­gram may no longer build!

The rea­son for this sig­nif­i­cance in com­pi­la­tion order is type infer­ence, a top­ic to be cov­ered lat­er on.

F# source files are com­piled in the order they are dis­played in Visu­al Studio’s Solu­tion Explor­er, from top to bot­tom. You can rearrange the files by right-click­ing and select­ing Move Up or Move Down. The equiv­a­lent key­board short­cuts are Alt+Up and Alt+Down, though these don’t seem to be work­ing in VS2008 with Resharp­er, or maybe I just need to tweak my key map­ping.