Table Of ContentCYAN YELLOW
MAGENTA BLACK
PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS® THE EXPERT’S VOICE® IN F#
Don Syme, Adam Granicz, Companion
and Antonio Cisternino, Expert F# 2.0 eBook Available
Authors of
Expert F#
Dear Reader, E
Functional programming is about concise, beautiful, and powerful code; and as x
you master the functional way of thinking you will get a boost in productivity and p
great personal enjoyment out of the clarity, compositionality, and brevity of your
e
programs.
In this book, you’ll learn about F# 2.0, an exciting young language that brings r
functional programming to .NET. F# 2.0 offers a unique combination of function- t Expert
al and object-oriented styles, has complete and seamless interoperability with
.NET, and has many features and characteristics of dynamic languages but with F
the performance of a compiled language.
Expert F# 2.0 is the single most complete and comprehensive guide to the lan-
F# 2.0
guage, including all of its advanced features such as active patterns, sequence
and computation expressions, quotations, units of measure, and lazy evaluation. #
Whether you’re using standard functional features such as pattern matching and
recursive functions or some unique F# features such as asynchronous workflows,
it becomes natural to write programs that spawn threads, model probabilistic
events, perform lightning-fast symbolic or numerical computations, translate
and manipulate language representations, describe server and client code for
web pages in a single entity, manipulate data using typed queries, draw cus-
2
tom UI controls, and interoperate with components built on unmanaged code,
to name only a few. All of these and more are demonstrated by example in this
book. Many of the examples are only a few lines long, and all are crafted with
care, ready for use in your applications.
.
For functional programmers, this book is full of treasures and a whole host of
practical guidance. If this is your first time with a functional language, look no
0
further—you are in for a treat and a great journey! We wish you bon voyage and
lots of fun on your exploration of this language.
Take functional programming to the next level
Don Syme, Adam Granicz, and Antonio Cisternino
while enjoying the benefits of a language based
Companion eBook on the .NET Framework
THE APRESS ROADMAP
Beginning F# Expert F# 2.0
See last page for details
on $10 eBook version
C
i
s Don Syme, Adam Granicz,
SOURCE CODE ONLINE tG
www.apress.com ISBN 978-1-4302-2431-0 ernran Sy Antonio Cisternino
56999 inicm and
oze
Shelve in
.NET
User level:
9 781430 224310
Intermediate–Advanced
this print for content only—size & color not accurate trim = 7.5" x 9.25" spine = 1.15625" 616 page count
Expert F# 2.0
■ ■ ■
Don Syme, Adam Granicz,
and Antonio Cisternino
Expert F# 2.0
Copyright © 2010 by Don Syme, Adam Granicz, and Antonio Cisternino
All rights reserved. No part of this work may be reproduced or transmitted in any form or by
any means, electronic or mechanical, including photocopying, recording, or by any
information storage or retrieval system, without the prior written permission of the copyright
owner and the publisher.
ISBN-13 (pbk): 978-1-4302- 2431-0
ISBN-13 (electronic): 978-1-4302-2432-7
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
President and Publisher: Paul Manning
Lead Editor: Jonathan Hassell
Technical Reviewer: André van Meulebrouck
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary
Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie,
Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke,
Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Anita Castro
Copy Editor: Tiffany Taylor
Compositor: Mary Sudul
Indexer: Brenda Miller
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-
[email protected], or visit www.springeronline.com.
For information on translations, please e-mail [email protected], or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or
promotional use. eBook versions and licenses are also available for most titles. For more
information, reference our Special Bulk Sales–eBook Licensing web page at
www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although
every precaution has been taken in the preparation of this work, neither the author(s) nor
Apress shall have any liability to any person or entity with respect to any loss or damage
caused or alleged to be caused directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com. You will need to answer
questions pertaining to this book in order to successfully download the code.
This book is dedicated to the memory of James Huddleston,
the editor at Apress who initiated this book project and
encouraged the authors with his insights, loyalty, enthusiasm, and humor.
Jim passed away in February 2007, an enormous loss to his family,
Apress, and the authors.
Contents at a Glance
Contents...................................................................................................................vi
Foreword...............................................................................................................xxi
About the Authors................................................................................................xxiii
About the Technical Reviewer.............................................................................xxiv
Acknowledgments..................................................................................................xv
■ Chapter 1: Introduction........................................................................................1
■ Chapter 2: Getting Started with F# and .NET........................................................7
■ Chapter 3: Creating Your First F# Program—
Introducing Functional Programming................................................................25
■ Chapter 4: Introducing Imperative Programming..............................................67
■ Chapter 5: Mastering Types and Generics.........................................................97
■ Chapter 6: Working with Objects and Modules................................................123
■ Chapter 7: Encapsulating and Packaging Your Code.......................................153
■ Chapter 8: Mastering F#: Common Techniques...............................................175
■ Chapter 9: Introducing Language-Oriented Programming...............................207
■ Chapter 10: Using the F# and .NET Libraries....................................................249
■ Chapter 11: Building Graphical User Interfaces...............................................271
■ Chapter 12: Working with Symbolic Representations.....................................321
■ Chapter 13: Reactive, Asynchronous, and Parallel Programming...................355
■ Chapter 14: Building Smart Web Applications.................................................391
■ Chapter 15: Working with Data........................................................................435
iv
■ Chapter 16: Lexing and Parsing.......................................................................463
■ Chapter 17: Interoperating with C and COM....................................................491
■ Chapter 18: Debugging and Testing F# Programs...........................................523
■ Chapter 19: Designing F# Libraries..................................................................545
■ Appendix: F# Brief Language Guide.................................................................563
Index.....................................................................................................................571
v
■ CONTENTS
Contents
Contents at a Glance................................................................................................iv
Foreword...............................................................................................................xxi
About the Author.................................................................................................xxiii
About the Technical Reviewer.............................................................................xxiv
Acknowledgments..................................................................................................xv
■ Chapter 1: Introduction........................................................................................1
The Genesis of F#............................................................................................................1
About This Book...............................................................................................................2
Who This Book Is For.......................................................................................................5
■ Chapter 2: Getting Started with F# and .NET........................................................7
Creating Your First F# Program.......................................................................................7
Documenting Code Using XMLDocs........................................................................................................9
Using let..................................................................................................................................................9
Understanding Types............................................................................................................................10
Calling Functions..................................................................................................................................11
Lightweight Syntax...............................................................................................................................12
Understanding Scope...........................................................................................................................13
Using Data Structures...........................................................................................................................14
Using Properties and the Dot-Notation.................................................................................................15
Using Tuples.........................................................................................................................................16
Using Imperative Code..........................................................................................................................18
Using .NET Libraries from F#.........................................................................................19
Using open to Access Namespaces and Modules................................................................................20
vi
■ CONTENTS
Using new and Setting Properties........................................................................................................21
Fetching a Web Page............................................................................................................................22
Summary.......................................................................................................................24
■ Chapter 3: Creating Your First F# Program—
Introducing Functional Programming................................................................25
Getting Started with F# Arithmetic................................................................................25
Basic Literals........................................................................................................................................25
Arithmetic Operators............................................................................................................................26
Bitwise Operations...............................................................................................................................27
Arithmetic Conversions........................................................................................................................28
Arithmetic Comparisons.......................................................................................................................29
Overloaded Math Functions..................................................................................................................29
Introducing Simple Strings............................................................................................30
Working with String Literals and Primitives.........................................................................................30
Building Strings....................................................................................................................................32
Working with Lists and Options.....................................................................................33
Using F# Lists.......................................................................................................................................33
Using F# Option Values.........................................................................................................................37
Using Option Values for Control............................................................................................................38
Working with Conditionals: && and ||............................................................................38
Defining Recursive Functions........................................................................................39
Introducing Function Values..........................................................................................40
Using Anonymous Function Values.......................................................................................................41
Computing with Aggregate Operators..................................................................................................42
Composing Functions with >>.............................................................................................................44
Building Functions with Partial Application..........................................................................................45
Using Local Functions..........................................................................................................................46
Using Functions as Abstract Values.....................................................................................................47
Iterating with Aggregate Operators......................................................................................................48
Abstracting Control with Functions......................................................................................................48
Using .NET Methods as First-Class Functions......................................................................................49
vii
■ CONTENTS
Getting Started with Pattern Matching..........................................................................50
Matching on Structured Values............................................................................................................51
Guarding Rules and Combining Patterns..............................................................................................53
Getting Started with Sequences....................................................................................53
Using Range Expressions.....................................................................................................................54
Iterating a Sequence............................................................................................................................55
Transforming Sequences with Aggregate Operators............................................................................55
Which Types Can Be Used as Sequences?...........................................................................................56
Using Lazy Sequences from External Sources.....................................................................................57
Using Sequence Expressions.........................................................................................58
Creating Sequence Expressions Using for............................................................................................58
Enriching Sequence Expressions with Additional Logic.......................................................................59
Generating Lists and Arrays Using Sequence Expressions..................................................................60
Exploring Some Simple Type Definitions.......................................................................60
Defining Type Abbreviations.................................................................................................................60
Defining Records..................................................................................................................................61
Handling Non-Unique Record Field Names..........................................................................................62
Cloning Records....................................................................................................................................63
Defining Discriminated Unions.............................................................................................................63
Using Discriminated Unions as Records...............................................................................................65
Defining Multiple Types Simultaneously..............................................................................................66
Summary.......................................................................................................................66
■ Chapter 4: Introducing Imperative Programming..............................................67
Imperative Looping and Interating.................................................................................68
Simple for Loops...................................................................................................................................68
Simple while Loops..............................................................................................................................68
More Iteration Loops over Sequences..................................................................................................69
Using Mutable Records..................................................................................................69
Mutable Reference Cells.......................................................................................................................70
Avoiding Aliasing..................................................................................................................................72
Hiding Mutable Data.............................................................................................................................73
Using Mutable Locals.....................................................................................................74
viii