Welcome to MSDN Blogs Sign in | Join | Help

View This Blog In

F# in VS2010

With Visual Studio, we strive to give your organization the tools to tackle a broad range of software problems with the interoperability and efficiency that you need and have come to expect from software based on the .NET Framework.

 

As part of this, Visual Studio 2010 marks the first release to directly support functional programming through the F# programming language.

 

F# is a highly productive .NET programming language combining functional programming and object-oriented programming, and is ideally suited for parallel, algorithmic, technical and explorative development.  F# is the result of a close partnership between Microsoft Research and the Visual Studio team, and since announcing F# in Visual Studio 2010 we’ve seen a surge of interest and uptake in the language. We’ve also worked closely with the F# community and major adopters to ensure it meets the needs of professional software developers working in these domains.

 

F# brings many new features to Visual Studio 2010, covering everything from “programming in the small” with Tuples and functions to simple, error-free asynchronous programming and strong types for floating point code.  Below are a few of the highlights of this addition to the Visual Studio languages.

 

Simple, Succinct Syntax

F# is a strongly-typed language like C#, but with a lightweight syntax often seen in a dynamic language like Python.  This gives your F# programs a lightweight, math-like feel.

 

let data = (1,2,3)

 

let rotations (x, y, z) =

    [ (x, y, z);

      (z, x, y);

      (y, z, x) ]

 

let derivative f x =

    let p1 = f (x - 0.05)

    let p2 = f (x + 0.05)

    (p2 - p1) / 0.1

 

let f x = 2.0*x*x - 6.0*x + 3.0

 

let df = derivative f

 

System.Console.WriteLine("The derivative of f at x=4 is {0}", df 4.0)

 

When run, this program will print: “The derivative of f at x=4 is 10

 

Parallel and Asynchronous Programming

.NET Framework 4 and Visual Studio 2010 contain great libraries and tools for easy parallel application development.  F# complements this with language features designed to make parallel and asynchronous programming more intuitive.  This includes fundamental language features like immutability and first-class functions, and powerful programming models, such as asynchronous workflows, which let you write asynchronous code in the same linear style as the synchronous code you are used to. 

 

let http url =

    async { let req =  WebRequest.Create(Uri url)

            let! resp = req.AsyncGetResponse()

            let stream = resp.GetResponseStream()

            let reader = new StreamReader(stream)

            let! contents = reader.AsyncReadToEnd()

            return contents }

 

let sites = ["http://bing.com"; "http://microsoft.com";

             "http://msdn.com"; "http://msnbc.com"]

 

let htmlOfSites =

    Async.Parallel [for site in sites -> http(site)]

    |> Async.RunSynchronously

 

 

Integrated with Visual Studio 2010 and .NET 4

F#’s integration in Visual Studio 2010 includes project templates, IDE support, IntelliSense and integration of the F# Interactive tool window.  F# can be used to develop applications and components targeting .NET 2.0 through .NET 4 and Silverlight.  As a .NET language, F# can be used comfortably alongside C# and Visual Basic.NET.  And in .NET 4, core types that F# uses, such as Tuple, Lazy, and BigInteger, are now part of the .NET Framework and can be used across all .NET languages.

 

The F# Interactive tool window enables an explorative development style within Visual Studio.  Below you can see the F# source code for an F# script open in the Visual Studio editor and the F# Interactive tool window where code is executed interactively.  At the top right is the Form and graphics that the script has created. 

 

F# Interactive tool window

 

Units of Measure

One ground-breaking feature of F# is Units of Measure, which allows you to annotate your floating point code with units, such as meters and seconds.  This is simple to do, and errors will be reported during development when code combines units incorrectly.  This provides compile-time checking of the correctness of floating-point code without sacrificing performance.

 

Units of Measure

That’s a quick look at just a few of the exciting features of F#.  For more on F#, visit the F# Development Center on MSDN.

 

Namaste!

Posted: Friday, October 09, 2009 10:21 PM by Somasegar

Comments

John said:

1st :D

Soma, pls fix the code examples. It would be great if one could just copy/paste them in VS.

Async example doesn't have the full name of classes specified. Does one still use 'open' keyword to import namespaces?

And the ray tracer code in text would be nice.

BTW when is VS beta 2 coming out? And what is the current estimate for RTM date?

# October 10, 2009 2:29 PM

John said:

OK, this took just a few hours, but now I have the 2nd example working. Fsharp PowerPack from CodePlex is required. The compiler gives a few warnings.

#light

open System

open System.IO

open System.Net

let http url =

   async { let req =  WebRequest.Create (url :> string)

           let! resp = req.AsyncGetResponse()

           let stream = resp.GetResponseStream()

           let reader = new StreamReader(stream)

           let! contents = reader.AsyncReadToEnd()

           return contents }

let sites = ["http://bing.com"; "http://microsoft.com";

            "http://msdn.com"; "http://msnbc.com"]

let htmlOfSites =

   Async.Parallel [for site in sites -> http(site)]

   |> Async.RunSynchronously

printfn "html: %a" output_any htmlOfSites

Console.ReadKey()

# October 10, 2009 6:34 PM

Luke Hoban said:

Hi John -

That's right, the async example requires the 3 open declarations you mention and the F# PowerPack.

The raytracer sample is similar to the F# Raytracer in the Parallel Samples for .Net 4.0 at http://code.msdn.microsoft.com/ParExtSamples.

More F# samples also at http://fsharp.net.  

# October 11, 2009 1:06 AM

SomeONe said:

It is nice to see F# moving along and being included with the other main stream languages. What I would like see is how to integrate it with other languages. A Visual Studio solution with a C# project referencing a F# project. Correct me if I'm wrong but I see F# as a complementary language. F# is a language to handle complex math easier than other languages but not to build a complete application with. One would use F# to build a library of intense math function. These math functions in an assembly would be referenced and used in a WPF, XNA, or Silverlight application written in C# or VB. If that is the case are there any examples showing that type of integration?  I see the ray tracing application but it looks to be bolted to Visual Studio. How could I build a Windows Form or WPF application to drive the ray tracing logic via C#? Maybe a game demo built with XNA using an F# library for the physic logic?

# October 12, 2009 9:00 AM

Somasegar said:

Hi John,

Stay tuned for news about VS 2010 Beta2 and beyond later this month.

-somasegar

# October 12, 2009 5:53 PM

contextfree said:

SomeONe:

For the most part you can expose classes and interfaces in your F# project and instantiate them, call their methods, subclass them etc. from C# like any other .NET class library.  If you expose types based on F#-specific features like pattern matching, workflows or units of measure, you can still use them from other languages but you'll have to know a bit about how those features are implemented and you won't get the benefits of them.

# October 13, 2009 10:11 AM

Mike Gale said:

The initial release of F# will (as far as I know) not be quite on a par with C# or VB.NET.  You don't automatically get it in th GAC, so in some deployment scenarios you have extra work to do.

My guess is that a lot of people are going to try the waters and really like them.  The code can, in some cases, just be so clean, lean and right that it will become the language of choice for some.

I'm really hoping that in a fairly short time it will become fully first class and just be installed everywhere like the main languages currently are.

# October 13, 2009 5:22 PM

Art Scott said:

Congratulations to Don Syme, and all those involved at Microsoft and in the community, in the brillant work to bring F# to this point.

I'm looking forward to a bright F#UN (read that BIG F# FUN) future. Using VS, F# and .NET to leverage the power of manycore CPUs and GPUs for visualization.

The future is bright,now and F#!

# October 14, 2009 3:29 AM

SomeONe said:

contextfree:

I know it can be done because that is one of the great things about .NET and the CIL/CLR . My question was more of where is a real world example of it being done. Not just the "in theory" discussions because it is .NET. Prove it by example.

Mike Gale:

IMHO I don't believe F# "will become fully first class (language)"

That is why there needs to be some kind of integration between the two. C# or VB.Net will be the first class language driving the UI/UX (if that be WinForm, WPF, or XNA, etc…) calling function in an F# library/assebmly.

Unless there are demos showing a complete application (menus, multiple forms, dialog boxes, tabs, combo box, etc…) written in F# driving the UI/UX and handling UI Events that otherwise would have been written in C# or VB.net. Or maybe a UI framework written completely in F# like MVC or MVVM or MVM? I'm thinking that is what C# and Vb.Net is for not F#.

I'm just wondering in the real world for consumer applications where F# fits. Or is meant as a lab tool for the Engineers and Scientist and is used in house.

I guess I know now what I need to work on. A C#/F# application.

# October 15, 2009 2:25 PM

Mike Gale said:

SomeOne (sic):

Your comment about first class misses what I'm saying.

In the narrow meaning I'm using here it becomes first class when it get's automatically distributed the same way that C# and VB.NET are "just there".

# October 15, 2009 3:20 PM

SomeONe said:

Mike Gale:

Got it, and from what I hear VS2010 it will be there. Even with the May 2009 Community Technology Preview.

To put the theory to practice is easy as alluded to in previous post. I knew and know it I just want to see it. The question as far as namespace, what an object name would be, what would I get returned from a function, do I need to reference F# in my C# all came to light.

I did the following got the code from http://fsharpsamples.codeplex.com/

1. Downloaded the May 2009 CTP.

2. Created a C# WPF application/solution.

3. Add a new F# Library Project

4. In this case I need to reference FSharp.Core in my c# project.

5. Made a reference in the C# to the F# project.

6. Copied the Fractal.fs from the samples to the F# project.

7. Copied the XAML from the sample to my C# application

8. Added to the XAML x:Class="CandFWPF.Window1"

9. Then add an Window_Loaded event handler coverted the F# to C#.

var br = new SolidColorBrush();

br.Color = Color.FromRgb(255, 255, 255);

var x = Fractal.CreateFractal();

this.fractal.Content = new GeometryModel3D(x.Item2, new DiffuseMaterial(br));

This is the line doing the call out to the F# assembly. Answers to questions, no name space, the class name is the file name. Function are static.

var x = Fractal.CreateFractal();

# October 16, 2009 11:03 AM

SomeONe said:

Now on to a bigger challenge QuotationsVisualizer. There seems to be a lot of code to write and handle GUI stuff. That is not math related and looks to me cumbersome in F#. I get complaints that at times C# is hard to read and interpret into English statement. Even with form designers and other GUI tools. I would hate for those people to try and read these:

member this.OpenFsAssembly () =

  let opf = new OpenFileDialog()

  opf.Filter <- "F# assemblies|*.dll;*.exe";

  match opf.ShowDialog(this) with

    | DialogResult.OK ->

        ResolveAssemblyDefinitions(opf.FileName)

          ( fun t ->

              let nd = new TreeNode(t.Name, 1, 1)

              ignore(exprTree.Nodes.Add(nd))

              nd )

          ( fun ndType mi exp ->

              let fn = new Text.StringBuilder()

              ignore(fn.AppendFormat("Loaded from assembly: {0}\r\n", mi.DeclaringType.Assembly.FullName));

              ignore(fn.Append("Declared in type: "));

              if (mi.DeclaringType.Namespace <> null) then ignore(fn.AppendFormat("{0}.", mi.DeclaringType.Namespace))

              ignore(fn.Append(mi.DeclaringType.Name));

              let nd = this.AddQuotationNode mi.Name (fn.ToString()) exp

              ignore(ndType.Nodes.Add(nd)) )          

    | _ -> ()

or this to build a Tree and assign properies and event handler:

  exprTree.Left <- 32

  exprTree.Width <- 200

  exprTree.Height <- 268

  exprTree.Top <- 288

  exprTree.HideSelection <- false

  exprTree.AfterSelect.Add(fun e ->

    if (e.Node.Tag <> null) then

      this.SelectPanel(e.Node.Tag :?> QuotationPanel))

# October 16, 2009 11:21 AM

Thanigainathan said:

Hi There,

This is very cool feature.

Thanks for letting us know this.

Thanks,

Thani

# October 21, 2009 2:37 AM

CA Reed said:

Will there be a F# Express product?

# October 22, 2009 8:16 AM

Luke Hoban said:

CA Reed -

There are no plans at this time for an F# Express with VS2010.  There will definitely continue to be free development tools for F# available though.

# October 22, 2009 10:43 AM

Adenegan Josiah said:

Created a Class Library (dll) in F# using VS 08 with the F# CTP October release.

Tried using the Assembly from VS2010 beta 1, after referencing the library (dll file generated by the F# Compiler) I can access the Namespaces in the library, but these namespaces vanish once I try to build the project and I can't henceforth access the referenced F# library.

It used to work with assemblies I built with the F# May CTP release, this problem started after i installed the October CTP

What could be wrong.

Thanks in advance.

# October 29, 2009 2:57 AM

Luke Hoban said:

Hi Adenegan -

Each F# CTP releases is matched with a Beta release of VS2010.  The October F# CTP can build libraries which can be be used in VS2010 Beta2.  If you still need to work with VS2010 Beta1, you'll want to contiue using the matching F# May CTP.  If you can, I'd encourage you to move to VS2010 Beta2, which has many improvements over the Beta1 release.

# October 29, 2009 9:44 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

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


Page view tracker