Programming F 3 0 Second Edition Chris Smith Instant Download
Programming F 3 0 Second Edition Chris Smith Instant Download
download
https://ebookname.com/product/programming-f-3-0-second-edition-
chris-smith/
https://ebookname.com/product/programming-c-sharp-3-0-5th-
edition-jesse-liberty/
https://ebookname.com/product/asp-net-3-5-website-programming-
chris-love/
https://ebookname.com/product/opengl-es-3-0-programming-
guide-2nd-edition-daniel-ginsburg/
https://ebookname.com/product/the-japan-that-never-was-
explaining-the-rise-and-decline-of-a-misunderstood-country-1st-
edition-dick-beason/
The international encyclopedia of ethics Volume 3 D Fal
1st Edition Hugh Lafollette
https://ebookname.com/product/the-international-encyclopedia-of-
ethics-volume-3-d-fal-1st-edition-hugh-lafollette/
https://ebookname.com/product/frommer-s-portable-maine-coast-
frommer-s-portable-4th-edition-paul-karr/
https://ebookname.com/product/technical-capabilities-necessary-
for-regulation-of-systemic-financial-risk-summary-of-a-
workshop-1st-edition-national-research-council/
https://ebookname.com/product/political-theory-without-
borders-1st-edition-robert-e-goodin/
Democracy and the Rule of Law in Classical Athens
Essays on Law Society and Politics Edward M. Harris
https://ebookname.com/product/democracy-and-the-rule-of-law-in-
classical-athens-essays-on-law-society-and-politics-edward-m-
harris/
O’Reilly Media, Inc. 4/2/2012
Preface
Have you ever been in a hurry and pounded in a nail using something other than a
hammer? Or perhaps settled an argument concerning distances with “the length of my
arm is about 20 inches, and that’s about two arm-lengths…?” You might not be willing to
fall for such obviously flawed short-cuts, but as your humble author I will admit that I
have.
There is elegance to using the right tool for the job. And, just like a hammer or a tape
measure, programming languages are tools like any other. Throughout this book you will
discover that while F# isn’t the best tool for every situation, it is the perfect tool for some
situations.
This book is about showing you how to use the F# programming language as a general-
purpose tool, with an emphasis on the specific domains where it can lead to dramatic
boots in productivity.
Along the way you will pick up a knack for functional programming; a semi-mysterious
collections of concepts that can help you rethink your programs regardless of the host
programming language.
Introducing F#
So what actually is F#? In a nutshell, F# is a multi-paradigm programming language built
on .NET, meaning that it supports several different styles of programming natively. I’ll
spare you the history of the language and instead just go over the big bullets:
• F# supports imperative programming. In F# you can modify the contents of memory,
read and write files, send data over the network, and so on.
• F# supports object-oriented programming. In F# you can abstract code into classes
and objects enabling you to simplify your code.
• F# supports functional programming, which is a style of programming which
emphasizes what a program should do, not explicitly how the program should work.
• F# is statically typed. Being statically typed means that type information is known at
compile time, leading to type-safe code. F# won’t allow you to put a square peg into
a round hole.
• F# is a .NET language. It runs on the Common Language Infrastructure (CLI) and so
it gets things like garbage collection (memory management) and powerful class
1
O’Reilly Media, Inc. 4/2/2012
libraries for free. F# also supports all .NET concepts natively, such as delegates,
enumerations, structures, P/Invoke, and so on.
Even without all the jargon, it is clear that F# is powerful language. But don’t worry;
we’ll cover it all step by step.
2
O’Reilly Media, Inc. 4/2/2012
3
O’Reilly Media, Inc. 4/2/2012
Chapter 15, Type Providers, explains the F# compiler’s special machinery for integrating
typed data across multiple domains. (Don’t fret, that sentence will make sense when you
start the chapter.)
Appendixes
This book also features a couple of appendixes to flesh out any extra concepts you might
be interested in.
Appendix A, Overview of the .NET Libraries, does a quick sweep through the existing
technologies available on the .NET platform and how to use them from F#.
Appendix B, F# Interop, covers how to write F# to interoperate with existing libraries as
well as unmanaged code using P/Invoke and COM-interop.
Notes like this are used to add more detail to the curious reader.
Warnings are indicated in this style are to help you avoid common
mistakes.
4
O’Reilly Media, Inc. 4/2/2012
Acknowledgments
In addition to the F# team at Microsoft for putting out a fantastic product, I’d like to
thank the following people for helping make the second edition of this book awesome:
Matt Douglass-Riely X
5
O’Reilly Media, Inc. 4/2/2012
Preface
Preface to the Second Edition
Hello! I’m writing this about three-years to the day that the first edition of Programming
F# came out. (And about one year before the second edition will be generally available.)
And it has been quite an experience.
Three years ago F# was just about to get its first official release in Visual Studio 2010.
Everyone on the team knew that developers would love our language, but we weren’t
sure where it would go. How it would be preceived.
But F# has not only been loved, it’s also achieved several important milestones. The first
one, was that this last year at the International Conference on Functional Programming
F# received the title as “the language for discriminating hackers”. While the
programming competition and “award” are just for fun, it demonstates that the language
isn’t just a toy.
Outside of the F# language front, the applications are growing. Job boards for F#
programmers are getting almost to much attention from head-hunters and recrutiers
aggressively looking to put F# developers in data mining, finance, and other technical
positions.
With that as the backdrop, there were a few key changes to the book for this second
edition aside from incorporating language advances for the F# 3.0 release.
First of all is the emphasis on more real-world examples. The first edition did a good job
of being a concise reference for the core language, but some readers left unsure of how to
actually apply F# to projects. This time around I’ve written dozens of large-scale
applications. To save space – again, to be concise – I’ve posted all the code on gitHub so
you can browse it freely and at your own pace at (github.com/achrissmith/programming-
fsharp/).
While with the explosive growth of mobile computing, F# in use as a server backend for
websites, and the unknown Windows 8 and the “Metro” UI style. It’s an exciting time to
be learning F# again!
1
O’Reilly Media, Inc. 4/2/2012
-Chris Smith
10/2011
Redmond, WA
2
O’Reilly Media, Inc. 4/2/2012
Part I
Multi-Paradigm Programming
1
O’Reilly Media, Inc. 4/2/2012
1
Introduction to F#
Getting to Know F#
As with all programming books, it is customary to write a Hello, World application, and I
don’t want to deviate from tradition. Open up Notepad or your favorite text editor and
create a new file named HelloWorld.fs with the following text:
// HelloWorld.fs
` 1
O’Reilly Media, Inc. 4/2/2012
C:\Programming F# Source\Ch01>HelloWorld.exe
Hello, World!
Visual Studio 11
Tools are the lifeblood of any programming language, and F# is no different. While you
can be successful writing F# code in your favorite text editor and invoking the compiler
from the command line, you’ll likely be more productive using tools. Like C# and
VB.NET, F# is a first-class citizen in Visual Studio with all the features that you might
expect, such as debugger support, IntelliSense, project templates, and so on.
Let’s revisit our Hello, World application, but this time using Visual Studio.
To create your first F# project, open up the Visual Studio IDE and select File → New
Project from the menu bar to open the New Project dialog, as shown in Figure 1-1. Select
Visual F# in the left pane, select F# Application in the right pane, and then click OK.
` 2
O’Reilly Media, Inc. 4/2/2012
open System
[<EntryPoint>]
let main (args : string[]) =
` 3
O’Reilly Media, Inc. 4/2/2012
Values
Example 1-1 introduces three values named greeting, thing, and timeOfDay.
let greeting, thing = args.[0], args.[1]
let timeOfDay = DateTime.Now.ToString("hh:mm tt")
The key thing here is that the let keyword binds a name to a value. It is worth pointing
out that unlike most other programming languages, in F# values are immutable by
default, meaning they cannot be changed once initialized. We will cover why values are
immutable in Chapter 3, but for now it is sufficient to say it has to do with “functional
programming”.
F# is also case-sensitive, so any two values with names that only differ by case are
considered different.
let number = 1
let Number = 2
let NUMBER = 3
You can enclose the value’s name with a pair of tick-marks, in which
case the name can contain any character except for tabs and new lines.
This allows you to refer to values and functions exposed from other
.NET languages that may conflict with F# keywords.
let ``this.Isn’t %A% good value Name$!@#`` = 5
Whitespace Matters
Other languages like C# use semicolons and curly braces to indicate when statements and
blocks of code are complete. However, programmers typically indent their code to make
it more readable anyways, so these extra symbols often just add syntactic clutter.
In F#, whitespace – spaces and newlines – is significant. The F# compiler allows you to
use whitespace to delimit code blocks. For example, anything indented more than the if
keyword is considered to be in the body of the if statement. Because tab characters can
indicate an unknown number of space characters, they are prohibited in F# code.
You can configure the Visual Studio editor to automatically convert tab
characters into spaces by changing the relevant setting under Tools →
Options → Text Editor → F#.
Reviewing Example 1-1, notice that the body of the main method was indented by four
spaces, and the body of the if statement was indented by another four spaces.
let main (args : string[]) =
` 4
O’Reilly Media, Inc. 4/2/2012
If the body of the if statement, the failwith "..." expression, was dedented four
spaces and therefore lined up with the if keyword, the F# compiler would produce a
warning. This is because the compiler wouldn’t be able to determine whether the
failwith was meant for the body of the if statement or the main function.
[<EntryPoint>]
let main (args : string[]) =
.NET Interop
Example 1-1 also demonstrates how F# can interoperate with existing .NET libraries.
open System
// ...
This example shows the DateTime.Now property from the System namespace in the
mscorlib.dll assembly in use.
The .NET Framework contains a broad array of libraries for everything from graphics to
databases to web services. F# can take advantage of any .NET library natively by calling
directly into it. Conversely, any code written in F# can be consumed by other .NET
languages. This also means that F# applications can run on any platform that supports
.NET. So the F# programs you write can run on phones, tablets, PCs, and so on.
Comments
F# allows you to comment your code. To declare a single-line comment use two slashes
//; everything after them until the end of the line will be ignored by the compiler.
` 5
O’Reilly Media, Inc. 4/2/2012
For larger comments you can use (* and *). Everything between the two tokens will be
ignored.
(*
Comment
spanning
multiple
lines
*)
For F# applications written in Visual Studio, there is a third type of comment – an XML
documentation comment. If a comment starting with three slashes, ///, is placed above
an identifier, Visual Studio will display the comment’s text when you hover the mouse
over the identifier.
Figure 1-3 shows applying an XML documentation comment and its associated tooltip.
F# Interactive
So far you have written some F# code and executed it, and the rest of the book will have
many more examples. While you could leave a wake of new projects to test out code,
Visual Studio comes with a tool called F# Interactive or FSI. The FSI window will not
only make it much easier to work through the examples in this book, but it will also help
you write applications.
F# Interactive is a tool known as a REPL, which stands for read, evaluate, print, loop. It
accepts F# code, compiles and executes it, then prints the results. This allows you to
quickly and easily experiment with F# without needing to create new projects or build a
full application to test the results of a code snippet.
Most Visual Studio configurations launch the F# Interactive window with the
Control+Alt+F keyboard combination. Once the FSI window is available, it accepts F#
` 6
O’Reilly Media, Inc. 4/2/2012
code until you terminate the input with ;; and a newline. The code entered is compiled
and executed as shown in Figure 1-4.
The FSI window prints any new values introduced as well as their types. Figure 1-4
shows val x : int = 42, declaring that a value x of type int was created with
value 42. If the FSI window evaluates an expression that was not assigned to a value, it
will instead assign it to the name it.
If you are running F# without Visual Studio, you can find the console
version of F# Interactive in the same directory you found fsc.exe
with the name fsi.exe.
Try running these other snippets in FSI. Remember that every code snippet is terminated
with a ;;.
> 2 + 2;;
val it : int = 4
> // Introduce two values
let x = 1
let y = 2.3;;
val x : int = 1
` 7
O’Reilly Media, Inc. 4/2/2012
The majority of the examples in this book are taken directly from FSI
sessions. I encourage you to use FSI to follow along and experiment
with the F# language’s syntax.
You can find a copy of the source code for all examples in the book on
GitHub at https://github.com/aChrisSmith/Programming-FS-
Examples/.
F# source files are compiled from top to bottom in the order they are displayed in Visual
Studio’s Solution Explorer. Whenever you add a new code, file it is added at the bottom
` 8
O’Reilly Media, Inc. 4/2/2012
of the list, but if you want to rearrange the source files you can right click a code file and
select “Move Up” or “Move Down” as seen in Figure 1-5. The keyboard shortcut for
reordering project files is Alt+Up and Alt+Down.
Now that you are armed with the logistical know-how for creating, compiling, and testing
F# applications, the rest of this book will focus exclusively on the syntax and semantics
of the F# programming language.
` 9
O’Reilly Media, Inc. 4/2/2012
In just a few chapters you’ll master the syntax of the F# language as well as be able to
apply it across several programming paradigms. Good luck and have fun!
` 10
O’Reilly Media, Inc. 4/2/2012
2
Fundamentals
In Chapter 1, you wrote your first F# program. I broke it down to give you a feel for what
you were doing, but much of the code is still a mystery. In this chapter, I’ll provide the
necessary foundation for you to understand that code fully, but more importantly, I’ll
present several more examples that you can use to grasp the basics of F# before you
move on to the more complex features.
The first section of this chapter covers primitive types, like int and string, which are
the building blocks for all F# programs. I’ll then cover functions so you can manipulate
data.
The fourth section details foundational types such as list, option, and unit.
Mastering these types will enable you to expand into the object-oriented and functional
styles of F# code covered in later chapters.
By the end of this chapter you will be able to write simple F# programs for processing
data. In future chapters you will learn how to add power and expressiveness to your code,
but for now let’s master the basics.
Primitive Types
A type is a concept or abstraction and is primarily about enforcing safety. Types represent
a proof of sorts if a conversion will work. Some types are straightforward – representing
an integer – while others are far more abstract – like a function. F# is statically typed,
meaning that type checking is done at compile-time. For example, if a function accepts an
integer as a parameter you will get a compiler error if you try to pass in a string.
Like C# and VB.NET, F# supports the full cast and crew of primitive .NET types. (Which
are standard across most programming languages.) They are built into the F# language
and separate from user-defined types which you define yourself.
To create a value, simply use a let binding via the let keyword. For example, the
following code defines a new value x in an FSI session. You can do much more with
let bindings, but we’ll save that for Chapter 3.
1
O’Reilly Media, Inc. 4/2/2012
val x : int = 1
Numeric Primitives
Numeric primitives come in two varieties: integers and floating-point numbers. Integer
types vary by size, so that some types take up less memory and can represent a smaller
range of numbers. Integers can also be signed or unsigned based on whether or not they
can represent negative values.
Floating-point types vary in size too; in exchange for taking up more memory they
provide more precision for the values they hold.
To define new numeric values, use a let binding followed by an integer or floating-
point literal with an optional suffix. The suffix determines the type of integer or floating-
point number. For a full list of available primitive numeric types and their suffixes, see
Table 2-1.
> let answerToEverything = 42UL;;
2
O’Reilly Media, Inc. 4/2/2012
> 0x00000000lf;;
val it : float32 = 0.0f
Arithmetic
You can use standard arithmetic operators on numeric primitives. Table 2-2 lists all
supported operators. Like most programming languages, integer division rounds down
discarding the remainder.
3
O’Reilly Media, Inc. 4/2/2012
By default arithmetic operators do not check for overflow, so if you exceed the range
allowed by an integer value by addition it will overflow to be negative. (Similarly,
subtraction will result in a positive number if the number is too small to be stored in the
integer type.)
> 32767s + 1s;;
val it : int16 = -32768s
F# features all the standard mathematical functions you would expect, with a full listing
in Table 2-3.
Conversion Routines
One of the tenets of the F# language is that there are no implicit conversions. This means
that the compiler will not automatically convert primitive data types for you behind the
scenes, such as converting an int16 to an int64. This eliminates subtle bugs by
removing surprise conversions. Instead, to convert primitive values you must use an
1
Power, the ** operator, only works for float and float32 types. To raise the power of an
integer value you must either convert it to a floating-point number first or use the pown function.
4
O’Reilly Media, Inc. 4/2/2012
explicit conversion function listed in Table 2-4. All of the standard conversion functions
accept all other primitive types – including strings and chars.
While these conversion routines accept strings, they parse strings using
the underling System.Convert family of methods, meaning that for
invalid inputs they throw System.FormatException exceptions.
BigInteger
If you are dealing with data larger than 264 F# has the bigint type for representing
arbitrarily large integers. (bigint type is simply an alias for the
System.Numerics.BigInteger type.)
bigint is integrated into the F# language; by using the I suffix for literals. Example 2-
1 defines data storage sizes as bigints.
Example 2-1. The BigInt type for representing large integers
> open System.Numerics
5
O’Reilly Media, Inc. 4/2/2012
Bitwise Operations
Primitive integer types support bitwise operators for manipulating values at a binary
level. Bitwise operators are typically used when reading and writing binary data from
files. See Table 2-5.
Characters
The .NET platform is based on Unicode, so most text is represented using 2-byte UTF-16
characters. To define a character value, you can put any Unicode character in single
quotes. Characters can also be specified using a Unicode hexadecimal character code.
The following snippet defines a list of vowel characters and prints the result of defining a
character using a hexadecimal value.
> let vowels = ['a'; 'e'; 'i'; 'o'; 'u'];;
\\ Backslash
\b Backspace
\n Newline
6
Discovering Diverse Content Through
Random Scribd Documents
GEORGE, PRINCE OF DENMARK
BY CHRISTIAN RICHTER
From the collection of Mr. E. M. Hodgkins
PLATE XII
MADAME DU BARRY
(1746-1793)
BY RICHARD COSWAY, R.A.
From the collection of Mr. J. Pierpont Morgan
PLATE XIII
VISCOUNTESS ST. ASAPH (NÉE LADY CHARLOTTE PERCY)
SECOND WIFE OF GEORGE, VISCOUNT ST. ASAPH, AFTERWARDS
THIRD EARL OF ASHBURNHAM
BY RICHARD COSWAY, R.A.
From the collection of Lord Hothfield
PLATE XIV
LADY AUGUSTA MURRAY WIFE OF THE DUKE OF SUSSEX
BY RICHARD COSWAY, R.A.
PLATE XV
LUCY, WIFE OF WILLIAM H. NASSAU, FOURTH EARL OF ROCHFORD
BY RICHARD COSWAY, R.A.
From the collection of Lord Hothfield
PLATE XVI
H.R.H. PRINCESS CHARLOTTE OF WALES
(1796-1817)
BY RICHARD COSWAY, R.A.
From the collection of Lord Hothfield
PLATE XVII
HENRY TUFTON, ELEVENTH AND LAST EARL OF THANET
(1775-1849)
BY RICHARD COSWAY, R.A.
From the collection of Lord Hothfield
PLATE XVIII
SIR CHARLES OAKELEY PORTRAIT OF A LADY
(1751-1826) (NAME UNKNOWN)
BY JOHN SMART BY JOHN SMART
PLATE XIX
PLATE XX
EARL BEAUCHAMP
BY GEORGE ENGLEHEART (1805)
From the collection of Lady Maria Ponsonby
PLATE XXI
MISS MARY BERRY
BY GEORGE ENGLEHEART
From the collection of Mr. J. Pierpont Morgan
PLATE XXII
MRS. SAINTHILL
BY GEORGE ENGLEHEART
PLATE XXIII
REBECCA, LADY NORTHWICK
(Ob. 1818)
BY ANDREW PLIMER
From the collection of Mr. J. Pierpont Morgan
PLATE XXIV
THE HON. HARRIET RUSHOUT
(Ob. 1851)
BY ANDREW PLIMER
PLATE XXV
ELIZABETH, MARGARET CAROLINE AND ANTOINETTE, DAUGHTERS OF JOHN ELLIS, ESQ.
OF HURLINGHAM, MIDDLESEX AND JAMAICA
BY ANDREW PLIMER
All from the collection of Lord Hothfield
PLATE XXVI
SELINA PLIMER
BY ANDREW PLIMER
From the collection of Dr. G.C. Williamson
PLATE XXVII
THE SISTERS RUSHOUT
BY ANDREW PLIMER
From the collection of Lord Hothfield
PLATE XXVIII
MRS. BAILEY, WIFE OF LIEUTENANT BAILEY, WHO WAS PRESENT
AT THE STORMING OF SERINGAPATAM IN 1799
BY ANDREW PLIMER
From the collection of Lord Hothfield
PLATE XXIX
SIR CHARLES KENT, BART., AS A CHILD
BY ANDREW PLIMER (1786)
From the collection of Lady Maria Ponsonby
MRS. DAWES
BY NATHANIEL PLIMER (1798)
From the collection of Lord Hothfield
PLATE XXX
CHARLOTTE, DUCHESS OF ALBANY, DAUGHTER OF
CHARLES EDWARD STUART BY CLEMENTINA,
TENTH DAUGHTER OF JOHN WALKENSHAW
(1753-1789)
BY OZIAS HUMPHRY
PLATE XXXI
LIEUTENANT LYGON
BY JOHN SMART, JUN. (1803)
From the collection of Lady Maria Ponsonby
PLATE XXXII
LADY MARY ELIZABETH NUGENT, AFTERWARDS MARCHIONESS
OF BUCKINGHAM, AND IN HER OWN RIGHT,
BARONESS NUGENT
(Ob. 1812)
BY HORACE HONE
From the collection of Lord Hothfield
PLATE XXXIII
MISS VINCENT
BY VASLET OF BATH
From the collection of Lord Hothfield
PLATE XXXIV
THE COUNTESS OF JERSEY
BY SIR GEORGE HAYTER (1819)
From the collection of Lady Maria Ponsonby
PLATE XXXV
LOUIS XIV
BY JEAN PETITOT, THE ELDER
From the collection of Mr. J. Ward Usher
PLATE XXXVI
CHARLES I.
BY P. PRIEUR
PLATE XXXVII
MADAME DUPIN
(Ob. 1799)
BY JEAN MARC NATTIER
THE COUNTESS SOPHIE LA PRINCESSE DE LAMBALLE
POTOCKI (Ob. 1792)
(Ob. 1822) BY P. A. HALL
BY P. A. HALL
PLATE XXXVIII
PORTRAIT OF A BOY
(NAME UNKNOWN)
BY JEAN HONORÉ FRAGONARD
PORTRAIT OF A LADY
(NAME UNKNOWN)
BY PIERRE PASQUIER (1786)
Both from the collection of Mr. J. Pierpont Morgan
PLATE XXXIX
PLATE XL
PLATE XLI
CATHARINE, COUNTESS BEAUCHAMP
BY JEAN BAPTISTE ISABEY
From the collection of Lady Maria Ponsonby
PLATE XLII
FÜRSTIN KATHARINA BAGRATION SKAWRONSKA
BY JEAN BAPTISTE ISABEY (1812)
From the collection of Fürst Franz Auersperg
PLATE XLIII
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com