Wednesday, March 31, 2010

Introducing F#

Introduction

The purpose of this article is to introduce you to the F# language - what it is, it's origins, and how it fits into Visual Studio 2010 RC. In the process, I hope to highlight the following:
  • What exactly is F#?
  • What is functional programming?
  • What are the benefits of functional programming?
  • How to install F#
  • What is F# Interactive?
  • The F# Powerpack
  • and where you can download the required F# tools and libraries from
In the Downloads section of this article you will find links to a presentation I gave on the F# language, as well as a Visual Studio 2010 solution containing sample F# projects and scripts you can run to further clarify what the language is and what it can do.

What is F#?

F# is a multi-paradigm programming language, targeting the .NET Framework, that encompasses functional programming as well as imperative object-oriented programming disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. F# was initially developed by Don Syme at Microsoft Research but is now being developed at Microsoft Developer Division and will be distributed as a fully supported language in the .NET framework and Visual Studio as part of Visual Studio 2010.

F# is a strongly typed language that uses type inference. As a result, data types need not be explicitly declared by the programmer; they will be deduced by the compiler during compilation. However, F# also allows explicit data type declaration. Being a .NET language, F# supports .NET types and objects. But itextends the type system and categorizes types as immutable types or mutable types. .NET objects classify as mutable types (which can be edited in-place), and are used to provide an object-oriented programming model. Immutable types (editing such a type creates a new instance without overwriting the older one) are primarily used for functional programming.

Before we can fully understand what F# is and how it fits into the bigger programming picture, we need to know a little more about functional programming.

What is Functional Programming?

Functional programming means that programs are executed by evaluating expressions. This contrasts with imperative programming where programs are composed of statements which change global state when executed. Functional programming, on the other hand, avoids using state and mutable data.

Functional programming requires that functions are first-class, which means that they are treated like any other values and can be passed as arguments to other functions or be returned as a result of a function. Being first-class also means that it is possible to define and manipulate functions nested in code blocks. Special attention needs to be given to nested functions, called closures, that reference local variables from their scope. If such a function escapes their block after being returned from it, the local variables must be retained in memory, as they might be needed later when the function is called. Usually it is not possible to determine statically the moment of release, which means that an automatic memory management technique has to be used.

Functional programming is based on the simplest of models, namely that of finding the value of an expression. This we meet in our first years at school, when we learn to work out expressions like 8+(3-2) by evaluating the two halves, 8 and (3-2), and adding the results together. Functional programming consists of our defining for ourselves functions like + which we can then use to form expressions.

We define these functions by means of equations, like

addD a b = 2*(a+b)

which we use to calculate the value of an expression like addD 2 (addD 3 4). We evaluate this using (1) to replace occurrences of addD with their values, so that we can write down a calculation of its value
addD 2 (addD 3 4)
=
2*(2 + (addD 3 4))
= 2*(2 + 2*(3 + 4))
= 32

As well as using (1) to calculate, we can read it as a logical description of how the function addD
behaves on any values a and b; on the basis of this we can reason about how it behaves. For instance, for any values a and b,

addD a b = 2*(a+b) =
2*(b+a) = addD b a
This equation holds for all possible input values, in contrast to the information we gain from testing a function at a selection of inputs.

On top of this simple model we can build a variety of facilities, which give the functional approach its distinctive flavour. These include higher-order functions, whose arguments and results are themselves functions; polymorphism, which allows a single definition to apply simultaneously to a collection of types; and infinite data structures which are used to model a variety of data objects.

The Miranda language also has support for larger-scale programming, including user-defined algebraic types, such as lists, trees and so on; abstract data types and modules. These contribute to separating complex tasks into smaller sub-tasks, making the components of systems independent of each other, as well as supporting software re-use.

Benefits of functional programming

Functional programming is known to provide better support for structured programming than imperative programming. To make a program structured it is necessary to develop abstractions and split it into components which interface each other with those abstractions. Functional languages aid this by making it easy to create clean and simple abstractions. It is easy, for instance, to abstract out a recurring piece of code by creating a higher-order function which will make the resulting code more declarative and comprehensible.

Functional programs are often shorter and easier to understand than their imperative
counterparts. Since various studies have shown that the average programmer's productivity in terms of lines of code is more or less the same for any programming language, this translates also to higher productivity.

F# Installation

F# is included as part of Visual Studio 2010. It comes with a Microsoft Visual Studio language service that integrates it with the IDE. With the language service installed, Visual Studio can be used to create F# projects and the Visual Studio debugger used to debug F# code. In addition, it comes with a Visual Studio-hosted interactive console that executes F# code as it is being written.

F# can also be downloaded as a seperate installation package for Visual Studio 2010 and 2010, or as a standalone compiler available in the F# CTP release. In addition to this, F# compiler binaries are also available for Mono, Mac, and Linux.

Furthermore, a collection of libraries and tools for use with the F# language is available in the form of the F# Powerpack from CodePlex.

What is F# Interactive

F# Interactive is a command line tool you can use to execute fragments of F# code interactively, making it a convenient way to explore the language.

You can start F# Interactive in Visual Studio by selecting Tools ➤ Add-in Manager and then selecting F# Interactive for Visual Studio in the Add-in Manager dialog box. A tool window will then appear, and you can send text to F# Interactive by selecting the text and pressing Alt+Return.

It is installed by default into %PROGRAMFILES%\Microsoft F#\v4.0 if Visual Studio 2010 is installed.

F# Powerpack

The F# PowerPack is a collection of libraries and tools for use with the F# programming language provided by the F# team at Microsoft.

This is functionality which is not part of the core F# release, but enables some development scenarios with F#. The PowerPack include features such as a basic Matrix library and supporting math types, FsLex and FsYacc tools for lexing and parsing, support for using F# with LINQ-based libraries, and a tool for generating HTML documentation from F# libraries. This functionality, which has previously been available in the F# CTP releases, is now available on CodePlex.

The PowerPack consists of several assemblies and tools which provide functionality in wide range of areas related to F#:

FsLex and FsYacc

PowerPack includes F# versions of these popular lexer and parser generation tools, along with MSBuild tasks to incorporate them in the build process.

F# Documentation generator

FsHtmlDoc.exe, included in PowerPack, can be used to generate HTML documentation from the XMLDoc comments in F# source files.

F# LINQ and Quotations to Expression Tree Bridge

FSharp.PowerPack.Linq.dll connects F# with features introduced in .NET 3.5. It provides converters from quotations to .NET expression trees, and introduces a query operator that allows F# programs to execute queries via LINQ mechanisms.

F# CodeDOM Implementation

FSharp.Compiler.CodeDom.dll contains implementations of System.CodeDom.Compiler.CodeDomProvider for F#. This allows F# to be used with CodeDom consumers, and most importantly to author ASP.NET pages code-behind classes in F#. Not all ASP.NET features work with this CodeDom, and you don't get strongly typed access to page elements, Some sample ASP.NET applications are in the test suite in the source tree.

F# Parallel LINQ Integration

FSharp.PowerPack.Parallel.dll provides F#-style API for parallel operations on sequences that are part in .NET 4.0 as System.Linq.ParallelEnumerable class. The API is akin to F# operations on sequences.

F# Metadata Reader

FSharp.PowerPack.Metadata.dll allows to introspect F#-authored assemblies and analyze F#-specific metadata.

F# Compatibility Helpers

FSharp.PowerPack.Compatibility.dll provides various helper functions for compatibility with OCaml and previous releases of F#.

Downloads

Also be sure to visit the Microsoft F# Research site.

Using the Code

Extract the source archive to your local hard drive.

The enclosed solution was created using Visual Studio 2010 RC, and contains six F# projects, and two F# script files (with an .fsx extension). To run a project, select a project of choice from the solution, right-click the project, select Set as StartUp Project, and hit F5!

To run the F# scripts, open the script file in Visual Studio 2010 RC, select all the code in the source file, and then either send the code to F# Interactive inside Visual Studio, or copy and paste the code into the F# Interactive command line tool.

No comments:

Post a Comment

Could you do me a SOLID mate?

Wow, it’s been a while! Nearly nine years since my last blog post . A lot has changed since then – some for the better, some for the worse....