Archives

Showing posts with label F#. Show all posts
Showing posts with label F#. Show all posts

Thursday, July 23, 2009

Do functional programmers need design patterns?

“Elements of Reusable Object-Oriented Software” is a book that I am sure all self respecting software developers have read. The infamous Gang of Four book seems to shape everything we do in modern object oriented software development and by applying the principles contained within generally results in a quality software product.

One common (but slightly controversial) view on design patterns is that generally they only exist to patch up any shortcomings of the language. If a language can solve a problem in a trivial way then it may well have no need for a design pattern at all. This can be demonstrated by developments within the .NET Framework, for example the “Iterator” design pattern is embedded within the language through the IEnumerable interface, reducing the need to implement the pattern yourself.

Microsoft F#, due to ship with Visual Studio 2010, is primarily a functional programming language and supports all the features you would expect, such as functions as first-class values, currying and immutable values. As F# is fully integrated into the .NET framework it can also be used in an imperative or object oriented way.

So in a multi-paradigm language is there a need for software design patterns? Do we need to worry about design patterns in F#, and if so how do we apply them.

Some articles I have read recently have gone so far as to suggest that the design of functional languages eliminates the need for design patterns completely. This is however only partially correct.

There are some design patterns that are rendered obsolete by functional languages, take the Command pattern as an example. The Command pattern as documented by the Gang of Four enables you to:

encapsulate a request as an object, letting you parameterize clients with different requests”.

This is simply an approximation of a first-class function. In F# you would simply pass a function as the argument to another function.

In an object oriented language, you have to wrap up the function in a class, which you then instantiate and pass the resulting object to the other function. The effect is the same, but in the object oriented world it's called a design pattern.

The same can be said about the Abstract Factory pattern. The Abstract Factory enables you to:

Provide an interface for creating families of related or dependent objects without specifying their concrete classes”.

In F# this is known as currying. Currying is the process of transforming a function that takes multiple arguments into a function that takes just a single argument and returns another function if any arguments are still needed.

It is clear therefore that several design patterns are rendered redundant in F# because the language provides more powerful, succinct alternatives. There are however still design problems that are not solved within F#. There is no F# equivalent for the Singleton pattern for instance.

Interestingly it works the other way too. Functional languages have their own design patterns; you just tend not to think of them that way. You may have come across “Monads”, which are a kind of abstract data type and often used for handling global state within functional languages. This is a problem that is so simple to solve in object oriented languages that there is no equivalent design pattern.

So while it is true that some object oriented design patterns become redundant in functional code, many, such as MVC do not.

So if you’re working with F#, don’t forget about design patterns, you never know you may even come across some new ones.

Read More >>

Friday, January 16, 2009

F# Language Basics

In this, the second post on F# I am going to walk through a simple application by way of an introduction to the language.

I am assuming that you have been able to download and install F#, which is freely available for Visual Studio 2008.  If not you can download it here: http://research.microsoft.com/fsharp

Creating a new F# project

Open Visual Studio 2008 and create a new project:

 

When creating a new F# project you have 3 options

·         F# Application

·         F# Library

·         F# Tutorial

An F# application creates a complete stand alone application that can be compiled into a standard .EXE file.

An F# Library allows you to create an assembly that you can then use in your other .NET applications.

The F# tutorial offers some pre generated code that allows you to quickly get up to speed with the language.

For this example you need to select F# Application.  Choose an appropriate name and location and then click OK.

Once the solution is created in Visual Studio you will be presented with the source code view of Program.fs which looks like this:

#light


Not particularly exciting and maybe even slightly confusing!

#light should always appear as the first (non comment) line of your application.  The reasons for this are complex and beyond the scope of this post so for now just accept it and lets hear no more about it!

The application that we are going to write will simply apply a calculation to every value in a list and display the results to the screen.  This is deliberately simple to highlight a few of the key concepts of the language.

In Visual Studio, enter the following code:

#light

let square x = x * x

This defines a function called square that returns the square of x.  To a mathematician this makes no sense at all as there is no known value where x is equal to x multiplied by x, however as programmers I trust your still with me!

There are two important things to notice here.  Firstly, the let keyword, which is one of the three most important keywords in F#.  Using let allows you bind a value to a symbol.  This should not be confused with a variable where you typically assign a value to a symbol.

The other important thing here is the lack of any type declaration.  If we were to write this function in C# we would have something like this:

public static int square(int x)

{

    return x * x;

}

Here we have to explicitly specify the type of x as well as the return data.  In F# the compiler infers this information automatically.  This is known as type inference.

Now we need to declare a list of integers from 1 to 15 (or higher if you like) so enter the following code:

let numbers = [1 .. 15]

Lists are the backbone of functional programming and in F# all lists are immutable linked lists.

Now we need to apply the function square to each value in the list numbers and we can do it without a single for loop by using the following code:

let squares = List.map square numbers

Now this is a little more complex so we can break this down as follows.

We are declaring a symbol called squares whose value is the result of evaluating the function: List.map square numbers

List.map generates a new collection whose elements are the result of applying a given function to each element of a collection.  It takes a function and a collection as parameters.

In essence what we are doing here is passing a function as a parameter to another function.  In functional programming, passing functions as values is known as first order functions and is a key concept in functional programming.

At this point your code should look like this:

#light

let square x = x * x

let numbers = [1 .. 15]

let squares = List.map square numbers

If you hover your mouse over squares, Visual Studio will tell you that this is a list of integers.  Type inference at work again!

To display the contents of sqaures we can use the following code:

printfn "Numbers squared = %A" squares

printfn is a simple (and type safe) way to print text to the console.  Where F# differs from C# is the use of a format specifier.  In this example we are using %A which is a general format specifier that prints any type.

Other format specifiers are:

%f – Prints floats

%b – Prints bools

%d – Prints integers

%s – Prints strings

Finally complete the application by adding the following code:

open System

Console.ReadLine()

open System tells the F# compiler to load the System namespace and bring it into scope.  This is the same as writing using System; in C#. 

This code shows how easy it is to use .NET libraries within your F# code and you really can call any library you like.

Console.ReadLine() just pauses the application so that you can see the output before the window closes.

Your finished application should look like this:

#light

let square x = x * x

let numbers = [1 .. 15]

let squares = List.map square numbers

printfn "Numbers squared = %A" squares

open System

Console.ReadLine()

Run the application and you should see the following output:

Hopefully this has given you a little insight into the potential of this language.  Next time I will get a little more in depth as we take on something a little more challenging!

 

Read More >>

Introduction to Microsoft F# - Part 1

I have recently been tasked with putting together some internal training materials on Microsoft’s new F# programming language. F# is a functional programming language, and in this post I aim to give you an overview of its many benefits and hopefully inspire you to add it to your development toolset. In later posts we will start delving into the language and get our hands dirty with some code.

As many of you may know, F# has been knocking around for some time now; originally starting out at Microsoft Research in Cambridge as a pet project of Don Syme. So popular has the language become that it is about to break into the mainstream when it is officially released as part of Visual Studio 2010.

So what is functional programming?

Functional programming is a method of programming that allows computation based upon the evaluation of mathematical functions. Typically a functional language does not contain state or mutable data and the emphasis is very much on the application of functions. Imperative and OO based languages such as C# however allow changes in state and data types within these languages are very often mutable.

Functional programming can trace its roots back to the early 1950 with languages such as LISP, however they have never really gained momentum outside of the academic and scientific domains.

As a .NET developer functional programming is not new to you. Features common place in .NET such as generics, and LINQ all have their roots in functional programming.

What does F# bring to the party?

F# brings typed functional programming to the .NET Framework. It is very succinct and expressive and allows for a new style of application development. As a (soon to be) fully CLR / CLS compliant language an F# application or library has full access to the entire range of .NET Framework APIs and is fully interoperable with other .NET languages such as C# and VB.NET.

Pure functional programming is often the best approach for solving complex computational problems however the traditional languages such as Haskel, Lisp and OCaml suffer with a lack of interoperability. F# is a natural extension of these languages in that it combines the 3 main programming paradigms (imperative, object orientated, and functional). Doing so gives us a general purpose .NET language that can be used in any style that takes your fancy! In fact you can use all three approaches within the same code.

One of the biggest benefits I have found in using F# is that not only is it a strongly typed language, it also offers excellent type inference. This means that as a developer you no longer need to explicitly specify a type. The only exception to this is when the type is ambiguous. I will look at this in more depth over the next few posts.

Why should I use F# ?

F# is the only .NET language to offer a combination of scripted, functional, object orientated and imperative programming. It allows you to solve highly complex computational tasks with relative ease and its fully supported by all other .NET languages. So if your ever faced with a problem that your struggling to solve in C#, give F# a go and see how easy it can be.

Where can I get F# ?

F# is currently a CTP release and is available for Visual Studio 2008. For more information on F# visit http://research.microsoft.com/fsharp
Read More >>