Welcome to MSDN Blogs Sign in | Join | Help

F#

A few weeks back, Soma blogged about an increased investment by the Microsoft Developer Division in the F# language.  Part of this increased investment has been the creation of a small team in Redmond to work with F#'s creator Don Syme to bring F# into the set of first class languages supported on .NET.  This provided a great opportunity for me to become one of the early members of this Redmond based F# team.  So, as of a few weeks ago, I've traded in my C# Compiler PM role for the newly created F# PM job!

As you can probably tell from some of my previous blog posts, I have a lot of interest in functional programming with .NET.  This makes F# is a naturally exciting language for me to be involved in.  F# provides a language in which functional programming is easy and expressive, while at the same time practical and well-connected to the underlying .NET type-system and programming model.  A exciting language for the .NET platform indeed!

Sample F# Code - Mandelbrot

Here's a little example piece of F# code to hopefully pique your interest to learn more about the language.

#light 
open Microsoft.FSharp.Math
open System

let maxIteration = 100

let modSquared (c : Complex) = c.r * c.r + c.i * c.i

type MandelbrotResult = 
    | DidNotEscape
    | Escaped of int
    
let mandelbrot c = 
    let rec mandelbrotInner z iterations = 
        if(modSquared z >= 4.0)
            then Escaped iterations
        elif iterations = maxIteration
            then DidNotEscape
        else mandelbrotInner ((z * z) + c) (iterations + 1)
    mandelbrotInner c 0

for y in [-1.0..0.1..1.0] do
    for x in [-2.0..0.05..1.0] do
        match mandelbrot (Complex.Create (x, y)) with
        | DidNotEscape -> Console.Write "#"
        | Escaped _ -> Console.Write " "
    Console.WriteLine () 
Let

The let keyword is used to declare a new variable or function.  Note in particular the similarities between the declaration of maxIterations and modSquared.  Functions are treated much the same as values of any other type throughout F#. 

Let can be used both at the top level and also inside function definitions to declare a local variable or function.  For example, the mandelbrot function uses a local function mandelbrotInner which computes the result, and simply calls it with the initial values.  Note also that mandelInner refers to the parameter c passed to the mandelbrot function - local functions are true closures.

Recursive function can be defined using let rec.

Types

F# is built on the .NET type system, and provides access to any type defined in a .NET assembly.  Types can also be defined in F# using the keyword type.  There are many kinds of types that can be created in F#, for example, standard .NET types such as classes and interfaces can be defined, but F# also supports types such as records and discriminated unions. 

As an example of discrimated unions, in the code above, MandelbrotResult is defined to be a type whose values are either DidNotEscape or are Escaped with an integer.  This accurately captures the mathematical definition of the mandelbrot set, which is defined in terms of points in the complex plane either escaping to infinity after a certain number of iterations, or remaining within a bounded region.

Terse Syntax

One of the most striking features of F# code is that it is very terse - ideas can typically be expressed with a small amount of code.  There are a few significant language features which contribute to this:

  1. Type Inference: F# is strongly typed, like C#, but instead of having to declare the type of variables, parameters and return types, F# uses type inference to determine these automatically.  When the types cannot be inferred, type annotations can be supplied in the code, such as in the definition of the modSquared function above.
  2. #light: The #light directive in F# allows code to omit begin...end keywords and some other tokens, and instead relies on indentation to indicate nesting.  This is similar to languages like Python, and enables the same kind of syntactic lightness that programs in these languages enjoy.
  3. Expressions: F# programs are built out of expressions, which can be composed very simply. For example, if is an expression in F#, as opposed to in C# where it is a statement.  This can make code simpler, while also enabling a high degree of flexibility.
Libraries

F# code can use all of the exisiting .NET libraries, such as the Console class used in the code above.  But F# also has access to a rich set of F# libraries, providing types that are well suited to functional programming and F# in particular.  A few notable libraries:

  1. Math:  One very useful example is the F# math libraries, representing datatypes such as Vector, Matrix, and BigNum, as well as the Complex numbers used in the code above.
  2. Collections:  The standard .NET Framework collections can be used from F#, but there is also a fully-featured set of functional collections, including the ubiquotous immutable linked list (List<A>), an efficient immutable set built on binary trees (Set<A>) and an immutable dictionary (Map<Key,A>)
  3. Control:  High-level control structures, such as compositional eventing (IEvent<A>), laziness (Lazy<A>) and most importantly, asynchronous programming primitives (ASync<A>).  The last of these in particular is a very exciting feature of F# for multi-threaded programming.
Interactive

F# comes with an "F# Interactive" toolwindow for Visual Studio, and also a command line interactive shell (fsi.exe).  These are tremendously useful for protyping and exploring, and can also be used as a testbed while working on larger projects.  As an example (see screenshot below) the code above can be pasted into an interactive shell to execute immediately.  If you want to make changes, just edit the code and paste into the interactive prompt again to run the new version.

Summary

Now that I'm working full-time on F#, you can expect to see more blogs posts here about F# in the future.  If you want to try out the code above, or any of the other great F# samples that are floating around the web, go to http://research.microsoft.com/fsharp/release.aspx and grab the most recent .msi download of the current Microsoft Research release of F#.

File iconmandelbrot.fs

Published Wednesday, November 14, 2007 6:57 PM by LukeH

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# MSDN Blog Postings &raquo; F#

Wednesday, November 14, 2007 7:51 PM by MSDN Blog Postings » F#

# re: F#

Wednesday, November 14, 2007 9:15 PM by derekslager

F# is a great language. I'm thrilled to see another resource for F# content, as that's the biggest weakness of the language at this point in time IMHO.

The best F# learning resource I've found thus far, in fact, is the O'Reilly OCaml book. As that's been my route to F# enlightenment, I'm rather impressed with the efforts made strictly in the name of compatibility.

Congratulations on the new position. Hope to see more good things coming from the F# team soon!

# re: F#

Thursday, November 15, 2007 5:17 AM by Tom Kirby-Green

Ditto. I'm really looking forward to reading your F# posts going forwards. I've just picked up a copy of Don Syme's new "Expert F#" book in ebook form from APress. It's so cool to see this language be promoted to the mainstream!

# F#, brought to you by Luke!

Thursday, November 15, 2007 9:34 AM by Don Syme's WebLog on F# and Other Research Projects

Luke Hoban is now full time as program manager on F#, and has just posted a short introduction about

# F#, brought to you by Luke

Thursday, November 15, 2007 10:06 AM by Noticias externas

Luke Hoban is now full time as program manager on F#, and has just posted a short introduction about

# re: F#

Thursday, November 15, 2007 6:19 PM by art_scott@msn.com

F# help in VS soon?

# re: F#

Thursday, November 15, 2007 7:27 PM by LukeH

art_scott -

Integrated F# help inside Visual Studio is certinaly one of the (many) things on our list of goals for F#.  No information yet on when we'll have this - but stay tuned!

# re: F#

Saturday, November 17, 2007 4:44 AM by Refik

I'd seriously consider using .Net platform if F# had a certified open source license. With F#'s current license Scala looks more attractive to me. I look forward to see an improvement on this aspect.

# Tight Code--A Puzzle in F#

Saturday, November 17, 2007 2:37 PM by Jomo Fisher -- C#, LINQ and Whatnot

Jomo Fisher--Luke Hoban wrote something in a blog entry that resonated with me: One of the most striking

# Tight Code--A Puzzle in F#

Saturday, November 17, 2007 2:59 PM by Noticias externas

Jomo Fisher--Luke Hoban wrote something in a blog entry that resonated with me: One of the most striking

# re: F#

Monday, November 19, 2007 10:48 AM by Julian Moeller

F# looks a lot like ML :-)

# re: F#

Monday, November 19, 2007 10:48 AM by Gnub

ML, anyone?

# re: F#

Monday, November 19, 2007 6:34 PM by Julian Moeller

I was actually wondering - will F# feature the same kind of higher order functions such as map and fold?

# re: F#

Tuesday, November 20, 2007 7:50 AM by LukeH

Julian and Gnub -

Yes, F# does look a lot like ML - in fact, it is a variant of ML, most closely related to OCaml.  There is a core of the F# language which is shared with OCaml.

# re: F#

Tuesday, November 20, 2007 7:56 AM by LukeH

Julian -

Higher order functions are indeed an important part of F#.  In particular, versions of "map" (which applies a function to each element of a collection) and "fold" (which walks across a collection building up a result as it goes) are available over most of the collection types in F#, such as lists, arrays, sets, etc.

# re: F#

Wednesday, November 21, 2007 1:59 PM by Chinedu Opara

Oh what an unfortunate language name. Couldn't you guys have chosen ANY of the other 20 or so remaining letters in the english alphabet? It HAD to be "F#"? HAH HAH

Well, I'm already building my library of "F"-word programming jokes...

# re: F#

Monday, December 17, 2007 10:23 AM by Gaurav

Great Luke...

Will like to catch u on a channel9 video for F# now...

Cum up with some interesting stuff at channel9...

Congratulations for new position...

I m really enjoying the F# world & learning the new language...

# re: F#

Tuesday, January 22, 2008 8:28 AM by Jay/R

Is it possible to get the current version of F# for VS 2005 somewhere?  I would like to install it and start working with it.  It sounds exciting!  Please advise.

# re: F#

Wednesday, January 23, 2008 10:50 PM by LukeH

Jay/R - The current downloads of F# are available at http://research.microsoft.com/fsharp/release.aspx.

# Lang.Net 2008

Monday, February 04, 2008 5:32 PM by Andy Norris

I loved the awesome interactive-console sample with the manifold and the rolling balls that you presented at Lang.Net 2008. Any chance you'll be posting that stuff here to play with?

# re: F#

Friday, February 08, 2008 5:13 PM by LukeH

Andy - The manifold and rolling balls demo I showed at Lang.NET is actually part of the samples that ship with the F# distrubution at http://research.microsoft.com/fsharp/research.aspx.  This sample is in Samples\FSharp\DirectX\3DVisualization\DirectX.fsharpp.

# re: F#

Monday, March 17, 2008 2:15 PM by Andrew Craven

Very impressive indeed! I also wrote my own LINQ mandelbrot set generator (in C#) a few days ago using many of your techniques from the raytracer - http://latebound.blogspot.com/2008/03/generating-fractals-with-linq.html.

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker