Software Development optimize

How do I... Get started using the F# programming language


This article is also available as a TechRepublic download.

F# (pronounced F Sharp) is a functional programming language based upon OCaml. It was developed by Microsoft's Microsoft Research department. All of the tools needed to run it are available for free from Microsoft.

F# runs within the .NET CLR, which means it can be used within existing .NET projects. Additionally, it can make use of any other .NET code. This overcomes a traditional weak spot for functional programming languages, namely a lack of libraries, utilities, and development environments. The F# language can stand alone, but it also plugs directly into Visual Studio. F# is noted for being very efficient in terms of the number of lines of code needed to accomplish particular tasks. It is also reported to run as quickly as C# -- and potentially even faster than C# for some tasks.

Installation

To install F#, you need to download the installation package. Unfortunately, the Microsoft F# Web site appears to be a bit out of date. To get the latest version of the software, go to the Microsoft Research Downloads section and perform a search for the F# Compiler. The most current version is F# 1.9.1.9, released May 1st, 2007. Installation is the same as any other Windows application and is quite easy. When you start Visual Studio, you will now see F# Research Compiler With Visual Studio added to the splash screen (Figure A).

Figure A

Visual Studio

Our first F# project

To give F# a try, start a new project in Visual Studio. Under the Other Project Types group, you will see F# Projects. There is currently only one template there (Figure B) but it is enough to get us started. Name this new project and click OK.

Figure B

F# template
You should now have an empty project. Unlike the standard Windows Forms or Web Application projects, the F# template does not create a lattice work of directories, default files, or anything of the type. Add a new item to the template, choosing F# Source File as the template (Figure C).

Figure C

F# source file
You will see that the new file has been added. Opening it shows that the F# template is filled with code that functions as a very basic tutorial. While this article will barely even be able to scratch the surface of F#, we will walk through a simple piece of code: a Fibonacci Sequence generator. This is a fairly standard, basic program for learning functional programming. We are going to use the standard definition of the Fibonacci Sequence. The code for the fib function is from the F# Manual. Here is our short little program (Listing A):

Listing A

// A Fibonacci Sequence generator

//Get the command line arguement as an integer type (Int32)

let fib_number = int_of_string (System.Environment.GetCommandLineArgs().GetValue(1).ToString());;

//Set the label "fib" to be equal to a Fibonacci Sequence function

let rec fib n =

if n < 2 then 1 else fib (n-2) + fib(n-1);;

//Print the input number and the Fibonacci sequence

Printf.printf "\nThe Fibonacci value of %u is: %u\n" fib_number (fib fib_number);;

//Exit the program, returning a normal status code to the OS

exit 0;;

The first line of the program is simply retrieving the second element of the command line arguments array (the first element is the executable name itself), converting it to an integer (F# is statically typed), and saving the value to a label named "fib_number". The second line defines a function with the label "fib". This function outputs the number 1 if the input (n) is less than 2; otherwise, it returns the sum of calling itself (the "rec" attribute marks the function as potentially recursive) with n - 1 and calling itself with n - 2. The third line prints our output using a very familiar printf syntax. Finally, the program exits.

This short little program demonstrates many interesting points of F#, which you will see if you step through the application in Visual Studio (be sure to specify a command line argument for the integer you want the Fibonacci sequence for). The most interesting item of note is the lazy evaluation. Lazy evaluation is the idea that the value of a label is assigned when that label is first used, instead of when the label is defined. In this case, stepping through the code (F11 in Visual Studio) with a watch on "fib_number" shows that although the label "fib_number" has been defined as the first line of the program, it does not get a value until "fib_number" is called by the printf function!

The next item of note in this sample is the use of recursion. By having a recursive function here, the number of lines of code is very small. While this example may be inefficient for large numbers (the stack usage can get rather high), and there are much more efficient ways to write this example in terms of speed, recursion is a technique that can solve many problems rather well.

The final point in this code sample is the ease of accessing the .NET Framework from within F#. The call to System.Environment.GetCommandLineArgs() works precisely as expected. Casting the resulting Object type to a string via the ToString method, and then casting it to an F# Int32 type by way of the int_of_string function does exactly what we would expect it to. While F# is statically typed like C#, Java, and many other compiled languages, it also performs type inference in the manner of languages like Perl.

Ending thoughts

F# is a rather unusual language within the .NET world. It can be compiled and called (and make calls to) any other code in .NET. At the same time, it also ships with an interactive runtime environment, which functions as a line-by-line interpreter. It has static typing like many compiled languages but also performs type inference like many dynamic and/or interpreted languages. It can be (but is not forced to be) object oriented as well.

The F# documentation itself is still rather sparse; for the sake of writing the short program above, it took me some time to find out how to cast the Object returned in the first line into an integer. That being said, the OCaml language has a large amount of documentation available for it. From the information on the F# Web site, it looks like F# does not stray too far from OCaml, but there are definitely some differences between the two. The Visual Studio integration is a nice bonus as well.

So go ahead and give F# a try! It is free, and you may learn some new coding techniques, even if you decide that F# is not for you.

About

Justin James is the Lead Architect for Conigent.

15 comments
satpal12021
satpal12021

Saltmarh Media is organizing this Great Indian Developer Summit event in Bangalore. This in a way will be a boost for the Software Developing Industry. It covers the topics like .Net, Java and Richweb and has 1 day workshop at the end as well. Any one attneding this event? Register @ www.developersummit.com

BALTHOR
BALTHOR

This is not a programming language this is script.I'm not kidding this code stuff is organized crime knocking us off the track!

demonhunterii
demonhunterii

Gonna have to agree with the others, but I'm thinking BALTHOR may have been to the F# webpage and having read a few bits and pieces there decided that it's a scripting language. Since the site does in fact mention scripting. Alot. Still, it's pretty cool to see some of this stuff filtering into a more mainstream light, and I for one will be interested in seeing how it goes. Can't help but think that perhaps some of the purity of ML is being sacraficed to fit in all the other features, but I guess I'll have to give it a go and find out... D.

Justin James
Justin James

While F# can be used dynamically like a scripting language, it is indeed a compiled language! It is not a scripting language at all. Indeed, my recollection is that the XBox gamer points system was re-written in F#, that is hardly a system of "Scripting" proportions! J.Ja

Mark Miller
Mark Miller

I checked BALTHOR out because his comment intrigued me. I looked through some of his other posts. He's a "drive by" post-er. He posts in topics like this and never returns. He appears to be a digital artist, and he knows a little something about computers, but he doesn't understand a wit about programming. Unfortunately he feels compelled to weigh in on all sorts of discussions he knows little to nothing about. He may have read an article that bashed scripting languages (I've seen them myself), and so saw your post on programming and thought you were demonstrating a scripting language. He's called C++ and Fortran "script code" as well... I think it's best if we ignored him. Anyway, it's cool that you got F# going. It's too bad they don't have starter templates for the different projects like console, Windows Forms, ASP.Net, and XML web service. Are you thinking of doing more with it?

apotheon
apotheon

"[i]Does it spoil the language? Absolutely not! It is still a very cool language that requires its own way of thinking to use.[/i]" This is at the center of the reason that, all else being equal, I think .NET is probably a good thing. If nothing else, it is introducing a bunch of people who would otherwise never have stepped out of the VisualFoo and J2EE mindset to some very interesting, or even (dare I say it?) [i]exciting[/i], languages. The danger is that they may think once they've used the .NET variant, such as F#, IronRuby, and so on, they're done -- they've learned all there is to know. It's just one (huge) step in the right direction, though -- it's not a complete journey toward truly experiencing all the wonders of learning a bunch of different and individually valuable languages. For instance, the REPL/script/bytecode/binary variety of execution options for OCaml itself also promotes changes in the programmer's mindset and approach to programming, as does the sublime module-based library system of OCaml proper. I've not really delved into OCaml enough to be able to start cranking out applications in the language, yet, but I've experienced enough to get a great 30k foot view of the language, and to whet my appetite. I'm in the middle of increasing familiarity and facility with a couple other languages right now (one of which is Ruby), but OCaml may well be next. If not, it'll probably only be a result of pursuing skills in kernel and driver hacking with C -- pushing OCaml back by one slot on my priority list. It's definitely something I intend to pursue in the nearish future, though, and in fact I'm interested in possibly creating a web browser in the language. Could be a lot of fun. The only downside to OCaml (the language -- there are some downsides to working with OCaml that aren't strictly related to the language itself) I've encountered so far is that strictly, strongly typed languages aren't so great for quick batch job scripts, even when they use type inference. Not a huge problem, of course, but certainly enough that there's no danger of abandoning Perl in favor of Ocaml.

Justin James
Justin James

Mark - Everything is getting well settled already! I got home late last night after the birth, spent the day with them, and retired back to the house to take care of the animals, get a meal, and prepare some food to take to her tomorrow. Everyone is well. It is a pretty good time so far. She was absolutely amazing throughout the whole thing, no matter how rough it got. Now I have to make some upgrades to my Web site software at home, and add in the photo gallery stuff, so I can easily get pictures up there in a way people can really use! J.Ja

apotheon
apotheon

"[i]the framework retains its own, Java-esque ways. This is mostly in terms of the name styles, but applies to a lot of other things as well. It just feels ugly.[/i]" Java is a very ugly language. Cloning the style of the Java syntax was both brilliant and monumentally stupid of Microsoft -- brilliant for marketing and quick adoption in "enterprise" shops, monumentally stupid in terms of actually enhancing programming practice. In fact, I'm pretty much convinced that the only reason Java programmers tend to think of Perl as the ugly child is that they see a couple regular expressions and sigil-marked variable names, and assume that they're going to end up looking at the same weight and volume of code they'd get with Java, only with a bunch of extra punctuation in it. That, of course, is pretty far from the truth. Not only is Java literally dozens, if not hundreds, of times as sprawling and lengthy as equivalent Perl code, but it's strung together in longer, more arbitrarily segmented, complex arrangements of chained methods. Enterprisey code I've seen tends toward a dozen or more chained methods in a single line of code, all to do the work of what should be maybe two or three methods or functions and an operator or two. Reasoning through a single line of Java is often at least as challenging an undertaking as reasoning through a full page of Perl. This is what Microsoft wanted to emulate with the .NET framework's libraries. It sure did catch the attention of a bunch of wannabe Java programmers -- Visual C++ code manufacturing assembly line workers who envied the relative ease of working with Java, mostly. It even drew in a bunch of Java programmers who were looking for a way to transition to desktop application and client development on MS Windows, so they wouldn't spend the rest of their lives working on things like Websphere and J2EE in the corporate offices of banking institutions. What it didn't do is actually improve the practice of programming itself, much. The only thing .NET has done for improving the practice of programming is make a bunch of alternative languages available as toys (since the real work in most MS shops is mostly limited to C# and VB). It's a step in the right direction, but nothing that wasn't already becoming available on the JVM in the form of things like Groovy, JRuby, and Jython, anyway. Anyway . . . I've rambled a bit. I'll move on before I ramble any more.

Justin James
Justin James

Everything you say here is 100% true. One thing I really have noticed in .Net is that regardless of the language, part of it will feel like C# or VB.Net, just because the Framework was designed with those languages in mind. It has been bugging me since I first picked it up, about 5 or so years ago. Since .Net was originally aimed at the same market as Java, it does feel very much like Java in many ways, right down to the method/property/class level. There are a good number of lines of code that can be used untouched in C# and J2EE without a single modification needed to work with the language *and* the framework. As a result, F# (along with Iron Python I am sure [I have not used it yet] and Ruby.Net/Iron Ruby/whatever they call it) lose a lot of their character. Microsoft's official definition of F# is a "ML variant" that is "similar to OCaml". If you are writing pure F# code (which translates down to .Net Framework objects, not directly to IL code like it could do), it looks most like OCaml, with no .Net-isms. But anything you do with the .Net Framework breaks the continuity, and I agree that it is icky. Does it spoil the language? Absolutely not! It is still a very cool language that requires its own way of thinking to use. But it snaps you out of the F# mindset to access the .Net Framework. It is one thing to use different languages in discrete chunks throughout a project or throughout your day, that is a gear shift which any intermediate and above developer should be able to handle. But the switch in mindset within lines of code is just a touch jarring. J.Ja

Justin James
Justin James

Yeah, you understood what I meant, basically make a "cheat sheet library" that has all of the calls to .Net I might use, and exposes them in a more language-appropriate way. That actually brings up my #1 pet peeve with the .Net Framework: regardless of the language conventions of the langugage I am using, the framework retains its own, Java-esque ways. This is mostly in terms of the name styles, but applies to a lot of other things as well. It just feels ugly. It is like when you work with a DB, do you name your tables & columns in the same style as the DB, or do you do it in a way that feels like the language that you are working in? J.Ja

Mark Miller
Mark Miller

Hey, you're a dad! :) I've got nothing better to say except that whatever's going on over there is far more important this this little forum. Take your time. We'll understand if you don't post as much. :)

apotheon
apotheon

"[i]I suspect that the smart coder would put a number of translation objects to convert from .Net objects to a more F#-like object, and use those to hide that mess.[/i]" I'm not entirely sure about there being a better way to do it. I don't know the ins and outs of the .NET framework well enough to really know for sure what's involved in the use of such translation objects, but I tend to think that using the quickest, easiest inclusion of your framework library functionality is probably the best for real-world programming. Segregating it visibly within the source code might make it easier to figure out what's going on, but more work than that for purely aesthetic reasons might just be unpragmatic. Then again, maybe I misunderstand what you mean. In any case, congratulations. Take your time getting back to this, of course, though I look forward to your response.

Justin James
Justin James

You make a ton of great points here. Just want to say (very quickly) that I agree that it is jarring at the very least to switch from the cleanliness of the F# langugage itself, to accessing the Java-esque ends of the .Net Framework (most of it). There may indeed be a better way to approach it, that was just the one I found off hand. I suspect that the smart coder would put a number of translation objects to convert from .Net objects to a more F#-like object, and use those to hide that mess. There is a lot more to reply here, but I will be out of commission for a few days, the baby just arrived! I stopped home to get some rest, and saw this excellent post here, that was begging to not be ignored. J.Ja

apotheon
apotheon

Every time I hear about how language such-and-such is now available on the .NET framework (speaking of languages that are actually interesting), I think "Neat!" and look for a little more information. Every time I actually encounter code showing how something was written in one of these .NET ports of interesting languages, however, I'm disappointed. In every case -- this case included -- I find that it looks like someone took a reasonable facsimile of the original language and shoehorned a bunch of Java classes into it. It's an especially jarring experience when I hear about something like F# and get a look at some example code. Compare the code for your Fibonacci generator, with its Java-like command line argument parsing syntax, with [url=http://www.ffconsultancy.com/ocaml/benefits/objects.html][b]object oriented code written in OCaml[/b][/url]. The syntax is not only distinctly different, but jarringly so. It's especially jarring to see such a Java-like syntax crop up in the middle of what amounts to a functional syntax like OCaml's. That's exactly the sort of thing that keeps turning me off of .NET and Mono (aside from the sheer weight of the runtime and library support needed for deployment, but that's another story altogether). I suspect that, for people who must work with .NET anyway, the essentially identical way to call out to framework libraries no matter the language used is surely a huge boon -- especially when someone wants to use a nonstandard language like F#. If I had to work with .NET, I'm sure I'd consider F# to be one of my druthers for a great number of reasons, including the succinctness of code necessary to achieve functionality goals. The framework library access is surely a huge benefit for people who want to learn from a number of differing syntactic styles in a hurry while still getting real work done, too -- you can switch between functional, Smalltalkish OOP syntax, C-like syntax, and nearly declarative syntaxes, all while still producing useful applications because the library calls all look the same and the weird new syntax you're learning is only really necessary for glue code. Just don't let yourself get lulled into believing you're learning differing languages. F# is not OCaml in a meaningful sense of the term, for instance -- or, at least, the way one uses it for most .NET development projects isn't anything like the way one uses OCaml itself. The likelihood of learning to think in OCaml (or anything like it) with F# is pretty slim, because the semantic underpinnings of the .NET framework tie you to a .NET way of thinking. That doesn't change the fact that it's a darn sight better than VB.NET if you have a choice. I've briefly brushed up against various incarnations of VisualBasic over the years, and my overwhelming impression has all along been that using it a lot runs a substantial risk of permanently damaging the programmer, in much the same way the original BASIC language did that to a lot of programmers. BASIC is the first programming language I learned, and I'm still recovering from the experience in some very subtle ways. I guess it's a bit like being an alcoholic: you never really finish recovering. I suspect the best thing you can do for yourself after learning enough of the F# syntax to get by is to use that to bootstrap yourself into actual OCaml use for a while. Go back to F# for work purposes once you've learned to think in OCaml, if you must, and while there will be some frustrating differences (like the way one makes library method calls), you'll have learned a lot about how the syntax in F# borrowed from OCaml can empower the programmer. This entire paragraph is all speculation, of course, since I've had only superficial experience with the .NET framework, at best -- but I suspect I'm on the right track. As for your comments about performance and lines of code compared with C#: I'm not surprised. The syntactic structure of F#, being borrowed from OCaml, is of course going to lead to very succinct code, just as OCaml's syntax allows much more succinct code to be written than you're likely to get out of C, C++, or Java. Performance could have gone either way, I think, because while F# had to be built on the .NET framework and thus could have suffered from some built-in limitations that would slow it down significantly, it's also based on probably the second-fastest general-purpose programming language sane people are likely to want to use. OCaml is not only faster than Java and C# (and F#, of course), but also blows even C++ out of the water. Only C itself consistently benchmarks faster than OCaml. If you really want the best performance object oriented code can give you, with the added benefit of an amazingly fast development cycle, I'm not sure there's anything out there that even comes close to OCaml. Thanks for the summarized review of F#, anyway. It was an interesting read, and gives me some hope that, if I ever find myself forced to write for .NET and/or Mono for a living, I might at least be able to use a language that doesn't drive me batty. PS, re the Java comparisons: It occurs to me, when you say that VB's verbosity makes it easy to figure out what it's doing, Java is the new COBOL -- but VB is the COBOL of a decade ago. It took until now for VB to get to the point where it's the COBOL of a decade ago, which means it's a little late to the table, but that's really how it seems to me. Its enforced verbosity and linearality are very much in line with the thinking behind the design of COBOL's syntactic and semantic structure way back in the day. Those of us who have been playing with programming languages for significant chunks of our lives, who actually enjoy working with code, will of course find COBOL code eye-clawingly ugly, but for someone trying to figure out what a piece of code was doing without knowing the language back when COBOL was the in-thing, there was nothing easier to figure out. The same is basically true of VB.NET today.

Justin James
Justin James

Mark - Thanks for the heads up on that one, I thought maybe I had misrepresented F#! Yes, I am hoping to be able to do some work with it. The gent at Microsoft (Syms, I beleive) says that when they rewrote the XBox Live gamer points system in it (coming from C#), they went from 10,000 SLOC to 1,000 SLOC (if I am remembering my numbers correctly) and that it ran as fast or faster. Where I am looking to use it is for matrix logic and searching. Once you go beyond a two dimenional decision system, to something requiring 3+ dimensions (particularly if the number of elements per dimension is not identical for each node at that level, ie a tree of logic), standard languages fall apart miserably! What are you going to do, have 5 levels of nested switch or select case statements, and if you need to make one changes, the number of times you need to make it is exponential! On the searching bit, I have a feeling that implementing some truly hardcore search logic in VB.Net, C#, or Java will not give our application the "secret sauce" to differentiate us in the market place. I need something that lets us code in some deep logic, with weightings of factors within a component, and weightings of the components themselves. I think that F# may give us an edge there, while still being quite fast. The lack of starter templates in indeed a shame. On the flip side, it is still better supported in Visual Studio than Iron Python, which is a much more high profile project. J.Ja