left-icon

F# Succinctly®
by Robert Pickering

Previous
Chapter

of
A
A
A

CHAPTER 2

First Steps in F#

First Steps in F#


This chapter will focus on a few general introductory details about the F# language and its programming environment. The next three chapters will focus on fleshing out the details of the language while this chapter will just offer a taste of what can be done. So don’t worry if you don’t understand all the details of the examples you see in this chapter, the rest of the book will fill them in.

Obtaining and Installing F#

The easiest and quickest way to get going with F# is to use Microsoft’s Visual Studio. F# is included with Visual Studio 2012 and 2010. If you do not have a copy of Visual Studio, you can download a free 90-day trial version from http://www.microsoft.com/visualstudio/try.

F# is installed by default with both Visual Studio 2012 and 2010, so just installing Visual Studio with the default options should be enough. If you have Visual Studio installed and F# isn’t available, you may have deactivated F# when installing Visual Studio. To activate F#, open Control Panel and go to the Programs menu.

If you don’t want to use F# with Visual Studio you can download a command-line compiler from Microsoft at http://www.microsoft.com/download/en/details.aspx?id=11100 and use your favorite text editor to edit F# source files. As I believe Visual Studio is the best way for beginners to experience F#, the rest of this chapter will assume you’re using Visual Studio, though all the examples will work with the command-line version of the compiler.

Hello World

As is traditional, let’s start with a “hello world” program in F#. First we need to create a Visual Studio project to host our program. To do this, navigate to File > New > Project… and select an F# Application.

Note: F# comes with only four pre-installed application or library templates. However, there are many more templates available online. These online templates have been contributed both by the F# team at Microsoft and the F# community. They can be searched and installed via Visual Studio’s New Project dialog.

Delete the contents in the program.fs file and enter the following line:

System.Console.WriteLine "Hello World"

Now press F5 to compile and execute the program and you’ll see the console briefly pop up with the “Hello World” greeting. Notice how the program is only one line long—this part of the philosophy of F#, that code should be as free as possible from syntactic clutter, and you’ll find this is a philosophy shared by many functional programming languages. We simply want to be able to call the System.Console.WriteLine method and pass it a string literal, so these are the only two elements of the program we need.

Since the program exits straight after the greeting is written to the console, the greeting text is probably on the screen too briefly for us to see it. Let’s fix that by reading a line from the console so the program will not exit until Enter is pressed:

open System

Console.WriteLine "Hello World"

Console.ReadLine()

Now press the F5 key again. When the program is executed this time, the greeting will stay until you press Enter and the program exits. Notice how we use the open keyword to open the System namespace. This allows us to remove the System from the beginning of the Console class’ name, and the compiler will still be able to find the class as it will now look for it in the System namespace. The open keyword is very similar to the using keyword in C# when it is used to import namespaces.

Using F# Interactive

Visual Studio comes with an interactive version of F# called F# Interactive. This is sometimes referred to as a read–eval–print loop, or REPL for short. It gives F# the feeling of a dynamic language as the programmer is able to interactively evaluate parts of his or her program and see the results immediately, although it should be noted that F# Interactive dynamically compiles the portions of code you pass to it, so you should see a similar level of performance to compiled F# code. To use F# Interactive, simply highlight the section of code you want to evaluate and press Alt+Enter. You’ll then see the results of this code printed in the F# Interactive window, usually located at the bottom of the screen. So if we highlight our initial "hello world" program and press Alt+Enter, we’d see the following results:

Hello World

val it : unit = ()

The first line is our greeting being output to the console. The second is some details about the program’s type—don’t worry too much about this for the moment. Types will be explained in a later chapter.

Being able to interactively execute code like this is one of my favorite features of F#. I think that being able to quickly try out ideas like this is a real productivity boost. So let's continue by looking at some other things you can do with F# Interactive, like creating interactive charts.

The F# team has created an F#-friendly wrapper for the System.Windows.​Forms.DataVisua​lization.Charti​ng.dll. The primary aim of this wrapper is to allow you to quickly show the data available in your program, or F# Interactive session, as a chart. It can be downloaded from http://code.msdn.microsoft.com/windowsdesktop/FSharpChart-b59073f5.

Once you unzip the downloaded FSharpChart folder, you will find the FSharpChart.fsx file inside the F# > Scripts folder. You’ll need to ensure this script is in the same directory as the F# script you’re working with, or modify the path to the script accordingly.

Now let’s take a look at how we use an F# chart. The following example shows how to create a chart showing a simple linear line:

#load "FSharpChart.fsx"

 

open MSDN.FSharp.Charting

let data = [ 1; 2; 3; 4 ]

FSharpChart.Line data

On inputting this program into F# Interactive, again via Alt+Enter, you’ll see a window pop up with the following chart:

Line Chart in F# Interactive

Figure 1: Line Chart in F# Interactive

Let’s take a look at how this program works. The first line loads the charting script, a file called FSharpChart.fsx, into the F# Interactive session. This line can take a few seconds as the charting script is quite large, but you only need to load it once, and the functions will continue to be available in the interactive session. The next line imports the namespace of the charting functions we’ll be working with. The following line creates a list of integers and binds them to the data identifier. Finally, we pass our list to the charting function FSharpChart.Line, which draws a line graph. This is not the world’s most exciting chart, so let’s take a look at another.

The following code sample will create a column chart showing dates and a value at each date:

#load "FSharpChart.fsx"

open System

open MSDN.FSharp.Charting

let dateInApril day = new DateTime(2012, 03, day)

let data = [ dateInApril 6, 4; dateInApril 7, 8;

             dateInApril 8, 2; dateInApril 9, 3 ]

FSharpChart.Column data

Again, on inputting this program into F# Interactive you’ll see a window pop up with the following chart:

 Column Chart in F# Interactive

Figure 2: Column Chart in F# Interactive

The top parts of the program, the part loading the FSharpChart.fsx script and the open statements, are pretty much the same as before. The first major difference is that we define a function, dateInApril, to provide a shorthand way to create a DateTime object in April 2012. Next you’ll notice our list of data is not single values, but pairs of values, referred to as tuples. Each pair contains a date object and an integer. Finally we pass our list of tuples to the charting function FSharpChart.Column which draws a column chart. While this chart is perhaps a little more interesting than the previous one, the example isn’t very realistic because we’re more likely to chart data from an external data source such as a text file.

So let’s look at how we might load some data from a .csv file and chart it with F#:

#load "FSharpChart.fsx"

open System

open System.IO

open MSDN.FSharp.Charting

let treatLine (line: string) =

    let stringParts = line.Split(';')

    DateTime.Parse stringParts.[0], int stringParts.[1]

let data =

    File.ReadAllLines (__SOURCE_DIRECTORY__ + "\\mydata.txt") 

    |> Array.map treatLine

   

FSharpChart.Column data

Yet again, the top part of the program changes little. After the open statements we define a function called treatLine that splits a line into two, parsing the first part as dates and the second as integers. Next we use .NET’s File.ReadAllLines function to read all the data from a text file called mydata.txt. After that we use the Array.map function to pass every line in the text file to our treatLine function and create a new array—this is very similar to using the LINQ extension method Select in C#. Finally, we pass the results to the FSharpChart.Column to draw the graph.

Summary

This chapter has given you a very brief introduction to using F#, both to create compiled programs and using F# Interactive to quickly test ideas. The remainder of the book will be a guide on how to program in F# by taking a detailed look at the language's syntax and features.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.