Cover

Table Of Contents

Table of Contents

The Story behind the Succinctly Series of Books

About the Author

Preface

Chapter 1   Introduction

Chapter 2   First Steps in F#

Chapter 3   Functional Programming

Chapter 4   Types and Type Inference

Chapter 5   Object-Oriented Programming

Chapter 6   Simulations and Graphics

Chapter 7   Form User Interfaces

Chapter 8   Creating an Application

Further Reading

Detailed Table of Contents

Preface

Preface

Using Code Examples

This book relies heavily on code examples to express F# concepts. The code samples are available at https://bitbucket.org/syncfusion/fsharp-succinctly.

Code samples are provided as individual Visual Studio F# project files. The samples are organized by chapter and named after the sub-headings of their respective chapters.

Most of the samples are console applications. From Visual Studio, if you run your application in debug mode (F5), the console window pops up and closes immediately. To view the sample result, use Start without debugging (Ctrl+F5). This will add a Press any key to continue prompt at the end of a console application, allowing you to close the console window by pressing any key.

Chapter 1 Introduction

Chapter 1  Introduction

This introductory chapter will address some of the major questions you may have about F# and functional programming (FP).

What Is Functional Programming?

What Is Functional Programming?

Pure functional programming views all programs as collections of functions that accept arguments and return values. Unlike imperative and object-oriented programming, it allows no side effects and uses recursion instead of loops for iteration. The functions in a functional program are very much like mathematical functions because they do not change the state of the program. In the simplest terms, once a value is assigned to an identifier it never changes, functions do not alter parameter values, and the results that functions return are completely new values. In typical underlying implementations, once a value is assigned to an area in memory, it does not change. To create results, functions copy values and then change the copies, leaving the original values free to be used by other functions and eventually be thrown away when no longer needed. (This is where the idea of garbage collection originated.)

The mathematical basis for pure functional programming is elegant, and FP therefore provides beautiful, succinct solutions for many computing problems, but its stateless and recursive nature makes the other paradigms convenient for handling many common programming tasks. However, one of F#’s great strengths is that you can use multiple paradigms and mix them to solve problems in the way you find most convenient.

Why Is Functional Programming Important?

Why Is Functional Programming Important?

When people think of functional programming, they often view its statelessness as a fatal flaw without considering its advantages. One could argue that since an imperative program is often 90 percent assignment, and a functional program has no assignment, a functional program could be 90 percent shorter. However, not many people are convinced by such arguments or attracted to the ascetic world of stateless recursive programming, as John Hughes pointed out in his classic paper “Why Functional Programming Matters.”

The functional programmer sounds rather like a medieval monk, denying himself the pleasures of life in the hope that it will make him virtuous.

John Hughes, Chalmers University of Technology
(http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html)

To see the advantages of functional programming, you must look at what FP permits rather than what it prohibits. For example, functional programming allows you to treat functions themselves as values and pass them to other functions. This might not seem all that important at first glance, but its implications are extraordinary. Eliminating the distinction between data and function means that many problems can be more naturally solved. Functional programs can be shorter and more modular than corresponding imperative and object-oriented programs.

In addition to treating functions as values, functional languages offer other features that borrow from mathematics and are not commonly found in imperative languages. For example, functional programming languages often offer curried functions, where arguments can be passed to a function one at a time and, if all arguments are not given, the result is a residual function waiting for the rest of its parameters. It’s also common for functional languages to offer type systems with much better power-to-weight ratios, providing more performance and correctness for less effort.

What Is F#?

What Is F#?

Functional programming is the best approach to solving many thorny computing problems, but pure FP often isn’t suitable for general-purpose programming. Because of this, FP languages have gradually embraced aspects of the imperative and OO paradigms, remaining true to the FP paradigm but incorporating features needed to easily write any kind of program. F# is a natural successor on this path. It is also much more than just an FP language.

Some of the most popular functional languages, including OCaml, Haskell, Lisp, and Scheme, have traditionally been implemented using custom runtimes, which leads to problems such as lack of interoperability. F# is a general-purpose programming language for .NET, a general-purpose runtime. F# smoothly integrates all three major programming paradigms. With F#, you can choose whichever paradigm works best to solve problems in the most effective way. You can do pure functional programming if you’re a purist, but you can easily combine functional, imperative, and object-oriented styles in the same program and exploit the strengths of each paradigm. Like other typed functional languages, F# is strongly typed but also uses inferred typing so programmers don’t need to spend time explicitly specifying types unless an ambiguity exists. Further, F# seamlessly integrates with the .NET Framework base class library (BCL). Using the BCL in F# is as simple as using it in C# or Visual Basic (and maybe even simpler).

F# was modeled on Objective Caml (OCaml), a successful object-oriented functional programming language, and then tweaked and extended to mesh well technically and philosophically with .NET. It fully embraces .NET and enables users to do everything that .NET allows. The F# compiler can compile for all implementations of the Common Language Infrastructure (CLI), it supports .NET generics without changing any code, and it even provides for inline Intermediate Language (IL) code. The F# compiler not only produces executables for any CLI, but can also run on any environment that has a CLI, which means F# is not limited to Windows but can run on Linux, Apple’s OS X and iOS, as well as Google’s Android OS.

The F# 2.0 compiler is distributed with Visual Studio 2012, Visual Studio 2010, and available as a plug-in for Visual Studio 2008. It supports IntelliSense expression completion and automatic expression checking. It also gives tooltips to show what types have been inferred for expressions. Programmers often comment that this really helps bring the language to life. F# 2.0 also has an open source release, licensed under the Apache License and is available from http://github.com/fsharp.

F# was fist implemented by Don Syme at Microsoft Research (MSR) in Cambridge. The project has now been embraced by Microsoft Corporate in Redmond, WA and the implementation of the compiler and Visual Studio integration is now developed by a team located in both Cambridge and Redmond. At the time of writing, the team was focused implementing F# 3.0, which is available in the Visual Studio “dev11” beta.

Although other FP languages run on .NET, F# has established itself as the de facto .NET functional programming language because of the quality of its implementation and its superb integration with .NET and Visual Studio.

No other .NET language is as easy to use and as flexible as F#!

Who Is Using F#?

Who Is Using F#?

F# has a strong presence inside Microsoft, both in MSR and throughout the company as a whole. Ralf Herbrich, coleader of MSR’s Applied Games Group, which specializes in machine learning techniques, is typical of F#’s growing number of fans:

The first application was parsing 110GB of log data spread over 11,000 text files in over 300 directories and importing it into a SQL database. The whole application is 90 lines long (including comments!) and finished the task of parsing the source files and importing the data in under 18 hours; that works out to a staggering 10,000 log lines processed per second! Note that I have not optimized the code at all but written the application in the most obvious way. I was truly astonished as I had planned at least a week of work for both coding and running the application.

The second application was an analysis of millions of feedbacks. We had developed the model equations and I literally just typed them in as an F# program; together with the reading-data-from-SQL-database and writing-results-to-MATLAB-data-file, the F# source code is 100 lines long (including comments). Again, I was astonished by the running time; the whole processing of the millions of data items takes 10 minutes on a standard desktop machine. My C# reference application (from some earlier tasks) is almost 1,000 lines long and is no faster. The whole job from developing the model equations to having first real world data results took 2 days.

Ralf Herbrich, Microsoft Research
(http://blogs.msdn.com/dsyme/archive/2006/04/01/566301.aspx)

F# usage outside Microsoft is also rapidly growing. I asked Chance Coble, CTO at Cyfeon Solutions, about what F# brought to his work.

F# has made its case to me over and over again. The first project I decided to try F# on was a machine vision endeavor, which would identify and extract fingerprints from submitted fingerprint cards and load them into a biometrics system. The project plan was to perform the fingerprint extraction manually, which was growing cumbersome and the automation turned out to be a huge win (with very little code). Later we decided to include that F# work in a larger application that had been written in C#, and accomplished the integration with ease. Since then I have used F# in projects for machine learning, domain-specific language design, 3-D visualizations, symbolic analysis, and anywhere performance intensive data processing has been required. The ability to easily integrate functional modules into existing production scale applications makes F# not only fun to work with, but an important addition for project leads. Unifying functional programming with a mature and rich platform like .NET has opened up a great deal of opportunity.

Chance Coble, CTO at Cyfeon Solutions (private email)

Who Is This Book For?

Who Is This Book For?

This book is aimed primarily at IT professionals who want to get up to speed quickly on F#. A working knowledge of the .NET Framework and some knowledge of either C# or Visual Basic would be nice, but it’s not necessary. All you really need is some experience programming in any language to be comfortable learning F#.

Even complete beginners who’ve never programmed before and are learning F# as their first computer language should find this book very readable. Though it doesn’t attempt to teach introductory programming per se, it does carefully present all the important details of F#.

Chapter 2 First Steps in F#

Chapter 2  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#

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

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

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.DataVisualization.Charting.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:

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:

 

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]

 

Impressum

Verlag: BookRix GmbH & Co. KG

Tag der Veröffentlichung: 06.02.2016
ISBN: 978-3-7396-3603-0

Alle Rechte vorbehalten

Nächste Seite
Seite 1 /