Learning F# – Part 1

I decided to take some time out on Silverlight and have a play around with Microsoft’s new language F#, I’ll be making notes as I go along and post them here so maybe they’d help satisfy some of your curiosity too!

Disclaimer: I do not claim credit for the code examples and much of the contents here, these are mostly extracts from the book by Chris Smith, Programming F#: A comprehensive guide for writing simple code to solve complex problems. In fact, if you’re thinking of learning F# and like what you read here, you should buy the book yourself, it’s easy to read and the author has gone go great lengths to keep things simple and included a lot of code examples for you to try out yourself.

Before you start, you need to download 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# Application, in Program.fs type in:

printfn “Hello, World”

Hit Ctrl+F5, and voila:

You might notice that your program worked without an explicit Main method.

Here’s a slightly more complex Hello, World to show off the syntax of F#:

image

The let keyword binds a name to a value, unlike most other programming languages, in F#, values are immutable by default (meaning they cannot be changed once initialized).

image

F# is also case-sensitive. The name of a variable can contain letters, numbers, underscore, or apostrophe (‘) and must begin with a letter or an underscore. However, you can enclose the value’s name with a pair of tickmarks in which case the name can contain any character except for tabs and newline:

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

printfn “%s, %s at %s” greeting thing “this.Isn’t %A% good value Name$!#“

Other languages like C# use semicolons and curly braces to indicate when statements and blocks of code are complete, but it clutters the code.

In F#, whitespace (spaces and newlines) is significant. The F# compiler allows you to use whitespace to delimit code blocks. For example, anything indented more than the if keyword is considered to be in the body of the if statement. Because tab characters can indicate an unknown number of space characters, they are prohibited in F# code. You can configure the Visual Studio editor to automatically convert tab characters into spaces in Tools -> Options -> Text Editor -> F#.

The earlier code also demonstrated how F# can interoperate with existing .Net libraries:

let timeOfDay = DateTime.Now.ToString(“hh:mm tt”)

F# can take advantage of any .Net library by calling directly into it, conversely any code written in F# can be consumed by other .Net languages.

Comments

Like any language, F# allows you to comment your code. To declare a single line comment, use two slashes (//).

For larger comments that span multiple lines, you can use the multiline comments using (* and *) characters.

For F# applications written in Visual Studio, there is a third type of comments: an XML documentation comment. If a comment starting with three slashes (///) is placed above an identifier, Visual Studio will display the comment’s text when you hover over it:

 


F# Interactive

Visual Studio comes with a tool called F# Interactive or FSI. F# Interactive is a tool known as a REPL (read-evaluate-print loop), it accepts F# code, compiles and executes it, then prints the results. This allows you to quickly and easily experiment with F# code similar to how snippet editor allows you to do the same with C# code.

Once it’s open, it accepts F# code until you terminate the input with ;; and a newline, the code entered will be compiled and executed. After each code snippet is sent to FSI, for every name introduced you will see val <name> : type value, for example:

Notice when you don’t give a variable a name, FSI will simply call it ‘it‘.

FSI allows you to write code in Visual Studio editor which offers syntax highlighting and IntelliSense, but test your code in the FSI window. You can copy the entire code body from the example earlier and test the main method in FSI by calling it:

Managing F# Source Files

The F# language has some unique characteristics when it comes to managing projects with multiple source files. In F#, the order in which code files are compiled is significant.

You can only call into functions and classes defined earlier in the code file or in a separate code file compiled before the file where the function or class is used. If you rearrange the order of the source files, your program may no longer build!

The reason for this significance in compilation order is type inference, a topic to be covered later on.

F# source files are compiled in the order they are displayed in Visual Studio’s Solution Explorer, from top to bottom. You can rearrange the files by right-clicking and selecting Move Up or Move Down. The equivalent keyboard shortcuts are Alt+Up and Alt+Down, though these don’t seem to be working in VS2008 with Resharper, or maybe I just need to tweak my key mapping.

Less is MORE

Just finished watching an interesting seminar video by the guys from Object Mentor (a consultant company founded by Robert C Martin, the father of agile development) at:

http://www.infoq.com/presentations/polyglot-polyparadigm-programming

The video is about an hour long and covered a large number of topics around using different languages (polyglot) and different programming paradigms (poly-paradigm) to simplify and speed up the software development process. The main thing I took away from this was:

“Less code is better, so less code is more. With less code, all your problems become smaller, be it maintenance, testing or performance.”

which most developers would agree I’m sure, after all, one of the reasons we refractor our code is so we end up with less code.

For young developers like myself, we have come into software development in an era dominated by the object oriented paradigm and a small handful of mainstream OO languages like C++, C# and Java. So for me at least, it’s refreshing to see how other paradigms and languages can be used in conjunction with those I’m familiar with to achieve:

  • greater productivity from the developers
  • more agile and extensible solution

Summary:

If you don’t have the time to watch the video (or simply not interested enough to do so!) then hopefully the list of key points I’ve compiled together would at least give you some idea what it’s all about:

  • There’s no silver bullet in software development
  • OO paradigm not always the best solution for the problem
  • Statically-typed languages (C#, C++, Java, etc.) are compiled for greater speed and efficiency at the cost of lowering productivity
  • Dynamically-typed language (ruby, python, JavaScript, etc.) are interpreted for greater extensibility, agility and productivity at the cost of lowering runtime performance
  • Ola Bini‘s Three layers – Domain layer (Domain Specific Languages), Dynamic layer (JRuby, etc.) and Stable layer (Java, C#, etc.)
  • Scripting languages increases pace of development
  • Aspect-oriented programming makes it easier to deal with cross-cutting concerns
  • Functional programming makes concurrency easier, because:
    • functions are side-effect free and stateless
    • nothing to synchronize, so no locks, semaphores, mutexes
  • Functional programming is cloud computing friendly
  • Functional languages and DSLs are more declarative than imperative
  • Scala is cool!
  • Advantages of the polyglot and poly-paradigm approach are:
    • able to use the best tool for a particular job
    • minimize the amount of code required and keep them closer to the domain
    • better decoupling between components
  • Disadvantages of this approach are:
    • multiple tools, languages, libraries to manage and learn
    • need to manage the different metadata models and overhead of calls between languages
  • It’s nothing new! For example, web developers often have to work in different paradigms and languages on a website
  • Higher end-user expectations and tighter schedules are driving the popularity of higher level languages such as functional and scripting languages
  • Developers have to deal context switching between different languages, so as the application grows larger and more complex, you have to start partitioning the teams (should be second nature to those working in the enterprise world!)

Parting thoughts..

As the presenter stated several times throughout, polyglot and poly-paradigm programming (PPP) has all been done before (despite now being mentioned with unfamiliar terminologies), and I certainly see a lot of familiarity of it in my line of work where in a typical 3-tiered application you’d have:

  • the data access layer using SQL (relational paradigm)
  • the business layer written in C#/Java or other OO languages
  • the UI can be in any number of different languages or paradigms depending on its form (HTML/CSS/Java/C#, etc.)

and numerous scripting languages (Perl, for example) are also used in various places (hell, after all, there are over 5000 applications being actively used within Credit Suisse alone!).

Watching this video has helped me identify with what I already know and put names (polyglot, poly-paradigm) to familiar faces (which is why jargon are important and I keep blogging about buzzwords :-P ), watch it, and see if it can help you too.

Further readings:

Ola Bini’s blog post on writing different layers of code in different languages