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!

Comments (33)

  1. John says:

    1st 😀

    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?

  2. John says:

    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()

  3. Luke Hoban says:

    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.  

  4. SomeONe says:

    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?

  5. Somasegar says:

    Hi John,

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

    -somasegar

  6. contextfree says:

    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.

  7. Mike Gale says:

    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.

  8. Art Scott says:

    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#!

  9. SomeONe says:

    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.

  10. Mike Gale says:

    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".

  11. SomeONe says:

    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();

  12. SomeONe says:

    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}rn", 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))

  13. Hi There,

    This is very cool feature.

    Thanks for letting us know this.

    Thanks,

    Thani

  14. CA Reed says:

    Will there be a F# Express product?

  15. Luke Hoban says:

    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.

  16. Adenegan Josiah says:

    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.

  17. Luke Hoban says:

    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.

  18. Ben says:

     let! contents = reader.AsyncReadToEnd()

    apears to be broken with Beta2 as you cant run the power pack

  19. Roger says:

    Ben,

    If you install the latest CTP download, you can use PowerPack with VS2010 Beta 2.

    Roger

  20. LukeH says:

    Hi Ben – As Roger mentioned, the F# PowerPack is available along with the F# October CTP, and can be used with either VS2008 or VS2010 Beta2.  A couple more details at http://msdn.microsoft.com/en-us/fsharp/cc835251.aspx.

  21. 3J says:

    As an Electrical Engineer now into Microsoft .NET development, I instantly saw the potential for F#. I just left a job where F# would make a *perfect* fit to replace their old, large, monolithic and extremely confusing FORTRAN library.

  22. luis says:

    hola

    quiero saber como graficar funciones en 3d en f# utilizando directx

    lpedraza1@cuc.edu.co

    gracias.

    hi

    I know how to plot functions in 3d in f # using directx

    lpedraza1@cuc.edu.co

    thanks.

  23. LukeH says:

    Hi Luis – The F# Samples contain some example code for polotting functions in 3D with DirectX interactively with F#.  See: http://code.msdn.microsoft.com/fsharpsamples

  24. Ravindra says:

    This is interesting news, looking forward for opportunities in VB to F# conversions etc.

  25. Qishen Huang says:

    This is a simple application that gives you some idea of what I’m looking for.

    Step 1:  My F# app asks the users to supply values for   variables X and Y.  Ex: X=1 and Y=2.

    Step 2.  My app asks the user at RUNTIME  what he wants to do with the data.  He writes F# script: for  X=X*Y and Y=Y-1.  It can be anything and can be complex.    Just any valid F# script.  

    ( This part gives the business user power to define computation at runtime.  )

    Step 3.  My app takes  the script and processes it.  Finally, the app writes value of Z to the screen.

    Do you have some sample like this?  Or is this possible?  Thanks!

    QishenHuang@yahoo.com

  26. Todd Jaspers says:

    Oh SWEET! This F# language looks awesome! I'm totally going to use this…

  27. driving lessons manchester says:

    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.<a href="http://www.localdrivinglessons4u.co.uk "> driving lessons manchester </a>

  28. sudershan says:

    Hi Soma,

    I got an site where I found how to generate .net document. I think it would be very much useful for us.

    when I tried for document generation system, I found a way to call it from .net, for this I found a way from this [http://www.dotnetdocgen.info/] site. It has basic info on all the vendors. It makes for a great starting point.

  29. Mike Bosch - Software Engineer says:

    Great News.

  30. ron says:

    Can I get vs 2010 f# to talk to common lisp?

  31. jopamer says:

    Hi Ron,

    We don’t explicitly provide support for interacting with Common Lisp, though an open-source .NET to CL bridge such as RDNZL (http://weitz.de/rdnzl/) may be what you're looking for.  Also, many commercial Common Lisp implementations provide mechanisms for static compilation to COM libraries, which would provide a bridging mechanism between CL and any .NET language.

    Thanks,

    Joe Pamer

    Dev Lead – F#

  32. boy says:

    Where can I download the F# language

  33. FsharpTeam says:

    @Boy: thanks for your interest!  There is more information on F# available on our team blog (blogs.msdn.com/…/fsharpteam). I recommend starting with the Visual Studio 2011 Developer Preview (go.microsoft.com/fwlink). See this post (blogs.msdn.com/…/f-3-0-developer-preview-now-available.aspx) for more information on what's new.