Tải bản đầy đủ (.pdf) (625 trang)

expert f# 2.0

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.1 MB, 625 trang )

Syme
Granicz
Cisternino
Expert
F# 2.0
Companion
eBook Available
this print for content only—size & color not accurate
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Shelve in
.NET
User level:
Intermediate–Advanced
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN 978-1-4302-2431-0
9 781430 224310
5 69 9 9
Expert F# 2.0
Dear Reader,
Functional programming is about concise, beautiful, and powerful code; and as
you master the functional way of thinking you will get a boost in productivity and
great personal enjoyment out of the clarity, compositionality, and brevity of your
programs.
In this book, you’ll learn about F# 2.0, an exciting young language that brings
functional programming to .NET. F# 2.0 offers a unique combination of function-


al and object-oriented styles, has complete and seamless interoperability with
.NET, and has many features and characteristics of dynamic languages but with
the performance of a compiled language.
Expert F# 2.0 is the single most complete and comprehensive guide to the lan-
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-
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
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.
Don Syme, Adam Granicz, and Antonio Cisternino
THE APRESS ROADMAP
Expert F# 2.0
Beginning F#
Don Syme, Adam Granicz,
and Antonio Cisternino,
Authors of
Expert F#
CYAN
MAGENTA

YELLOW
BLACK
PANTONE 123 C
trim = 7.5" x 9.25" spine = 1.15625" 616 page count
Expert
F# 2.0
Don Syme, Adam Granicz,
and Antonio Cisternino
Take functional programming to the next level
while enjoying the benefits of a language based
on the .NET Framework
THE EXPERT’S VOICE
®
IN F#
www.it-ebooks.info
www.it-ebooks.info
Expert F# 2.0











■ ■ ■
Don Syme, Adam Granicz,

and Antonio Cisternino


www.it-ebooks.info
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-

, or visit www.springeronline.com.
For information on translations, please e-mail , 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.

www.it-ebooks.info








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.





www.it-ebooks.info

iv

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
www.it-ebooks.info

v

■ 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
www.it-ebooks.info
■ CONTENTS

vi

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
www.it-ebooks.info
■ CONTENTS

vii

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

www.it-ebooks.info
■ CONTENTS

viii

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

www.it-ebooks.info
■ CONTENTS

ix

Working with Arrays 74
Generating and Slicing Arrays 76
Two-Dimensional Arrays 77
Introducing the Imperative .NET Collections 77
Using Resizeable Arrays 78
Using Dictionaries 79
Using Dictionary's TryGetValue 79
Using Dictionaries with Compound Keys 80
Some Other Mutable Data Structures 81
Exceptions and Controlling Them 81
Catching Exceptions 83
Using try . . . finally 83
Defining New Exception Types 84
Having an Effect: Basic I/O 85
Very Simple I/O: Reading and Writing Files 85
.NET I/O via Streams 86
Some Other I/O-Related Types 87
Using System.Console 88
Using printf and Friends 88
Generic Structural Formatting 90
Cleaning Up with IDisposable, use, and using 90
Working with null Values 91
Some Advice: Functional Programming with Side Effects 92
Consider Replacing Mutable Locals and Loops with Recursion 93
Separate Pure Computation from Side-Effecting Computations 93

Separate Mutable Data Structures 93
Not All Side Effects Are Equal 94
Avoid Combining Imperative Programming and Laziness 95
Summary 96
■ Chapter 5: Mastering Types and Generics 97
Understanding Generic Type Variables 97
Writing Generic Functions 98
www.it-ebooks.info
■ CONTENTS

x

Understanding Some Important Generic Functions 99
Generic Comparison 99
Generic Hashing 100
Generic Pretty-Printing 101
Generic Boxing and Unboxing 101
Generic Binary Serialization via the .NET Libraries 102
Making Things Generic 104
Generic Algorithms through Explicit Arguments 104
Generic Algorithms through Abstract Object Types 106
Arithmetic Operators and Generic Algorithms through Inlining 108
Understanding .NET Types 109
Reference Types and Value Types 109
Other Flavors of .NET Types 110
Understanding Subtyping 111
Casting Up Statically 111
Casting Down Dynamically 111
Performing Type Tests via Pattern Matching 112
Knowing When Upcasts Are Applied Automatically 113

Flexible Types 114
Units of Measure 115
Troubleshooting Type-Inference Problems 117
Using a Visual Editing Environment 117
Using Type Annotations 117
Understanding the Value Restriction 118
Working Around the Value Restriction 119
Understanding Generic Overloaded Operators 121
Summary 122
■ Chapter 6: Working with Objects and Modules 123
Getting Started with Objects and Members 123
Using Classes 126
Adding Further Object Notation to Your Types 130
Working with Indexer Properties 130
www.it-ebooks.info
■ CONTENTS

xi

Adding Overloaded Operators 130
Using Named and Optional Arguments 132
Using Optional Property Settings 133
Adding Method Overloading 134
Defining Object Types with Mutable State 135
Getting Started with Object Interface Types 137
Defining New Object Interface Types 138
Implementing Object Interface Types Using Object Expressions 139
Implementing Object Interface Types Using Concrete Types 140
Using Common Object Interface Types from the .NET Libraries 141
Understanding Hierarchies of Object Interface Types 142

More Techniques to Implement Objects 143
Combining Object Expressions and Function Parameters 143
Defining Partially Implemented Class Types 144
Using Partially Implemented Types via Delegation 145
Using Partially Implemented Types via Implementation Inheritance 145
Using Modules and Static Members 147
Extending Existing Types and Modules 148
Working with F# Objects and .NET Types 150
Structs 151
Delegates 151
Enums 151
Summary 152
■ Chapter 7: Encapsulating and Packaging Your Code 153
Hiding Things Away 153
Hiding Things with Local Definitions 154
Hiding Things with Accessibility Annotations 156
Using Namespaces and Modules 159
Putting Your Code in a Namespace 159
Using Files as Modules 160
Creating Assemblies, DLLs, and EXEs 161
Compiling EXEs 161
www.it-ebooks.info
■ CONTENTS

xii

Compiling DLLs 161
Mixing Scripting and Compiled Code 163
Choosing Optimization Settings 164
Generating Documentation 164

Building Shared Libraries and Using the Global Assembly Cache 165
Using Static Linking 166
Using Signature Types and Files 167
Using Explicit Signature Types and Signature Files 167
When Are Signature Types Checked? 168
Packaging Applications 169
Packaging Different Kinds of Code 169
Using Data and Configuration Settings 170
Summary 173
■ Chapter 8: Mastering F#: Common Techniques 175
Equality, Hashing, and Comparison 175
Asserting Equality, Hashing, and Comparison Using Attributes 176
Fully Customizing Equality, Hashing, and Comparison on a Type 177
Suppressing Equality, Hashing, and Comparison on a Type 179
Customizing Generic Collection Types 179
Efficient Precomputation and Caching 180
Precomputation and Partial Application 180
Precomputation and Objects 182
Memoizing Computations 183
Lazy Values 185
Other Variations on Caching and Memoization 186
Cleaning Up Resources 186
Cleaning Up with use 187
Managing Resources with More Complex Lifetimes 189
Cleaning Up Internal Objects 190
Cleaning Up Unmanaged Objects 191
Cleaning Up in Sequence Expressions 192
Using using 194
www.it-ebooks.info
■ CONTENTS


xiii

Stack as a Resource: Tail Calls and Recursion 194
Tail Recursion and List Processing 195
Tail Recursion and Object-Oriented Programming 197
Tail Recursion and Processing Unbalanced Trees 198
Using Continuations to Avoid Stack Overflows 199
Another Example: Processing Syntax Trees 201
Events 202
Events as First-Class Values 203
Creating and Publishing Events 204
Summary 205
■ Chapter 9: Introducing Language-Oriented Programming 207
Using XML as a Concrete Language Format 208
Using the System.Xml Namespace 208
From Concrete XML to Abstract Syntax 210

Working with Abstract Syntax Representations 213
Abstract Syntax Representations: Less Is More 213
Processing Abstract Syntax Representations 213
Transformational Traversals of Abstract Syntax Representations 215
Using On-Demand Computation with Abstract Syntax Trees 215
Caching Properties in Abstract Syntax Trees 217
Memoizing Construction of Syntax Tree Nodes 218
Introducing Active Patterns 220
Converting the Same Data to Many Views 220
Matching on .NET Object Types 222
Defining Partial and Parameterized Active Patterns 223
Hiding Abstract Syntax Implementations with Active Patterns 223

Embedded Computational Languages with Workflows 225
An Example: Success/Failure Workflows 227
Defining a Workflow Builder 230
Workflows and Untamed Side Effects 232
Example: Probabilistic Workflows 233
www.it-ebooks.info
■ CONTENTS

xiv

Combining Workflows and Resources 238
Recursive Workflow Expressions 238
Using F# Reflection 239
Reflecting on Types 239
Schema Compilation by Reflecting on Types 239
Using the F# Dynamic Reflection Operators 243
Using F# Quotations 244
Example: Using F# Quotations for Error Estimation 245
Resolving Top Definitions 247
Summary 248
■ Chapter 10: Using the F# and .NET Libraries 249
A High-Level Overview 249
Namespaces from the .NET Framework 250
Namespaces from the F# Libraries 252
Using the System Types 253
Using Regular Expressions and Formatting 255
Matching with System.Text.RegularExpressions 255
Formatting Strings Using .NET Formatting 260
Encoding and Decoding Unicode Strings 261
Encoding and Decoding Binary Data 262

Using Further F# and .NET Data Structures 262
System.Collections.Generic and Other .NET Collections 262
Introducing Microsoft.FSharp.Math 263
Using Matrices and Vectors 263
Using Operator Overloads on Matrices and Vectors 265
Supervising and Isolating Execution 265
Further Libraries for Reflective Techniques 266
Using General Types 266
Using Microsoft.FSharp.Reflection 267
Some Other .NET Types You May Encounter 267
Some Other .NET Libraries 268
Summary 269
www.it-ebooks.info
■ CONTENTS

xv

■ Chapter 11: Building Graphical User Interfaces 271
Writing “Hello, World!” in a Click 271
Understanding the Anatomy of a Graphical Application 272
Composing User Interfaces 273
Drawing Applications 278
Writing Your Own Controls 282
Developing a Custom Control 282
Anatomy of a Control 285
Displaying Samples from Sensors 286
Building the GraphControl: The Model 288
Building the GraphControl: Style Properties and Controller 290
Building the GraphControl: The View 293
Putting It Together 297

Creating a Mandelbrot Viewer 298
Computing Mandelbrot 299
Setting Colors 300
Creating the Visualization Application 303
Creating the Application Plumbing 305
Windows Presentation Foundation 309
When GUIs Meet the Web 311
Drawing 312
Controls 315
Bitmaps and Images 318
Final Considerations 320
Summary 320
■ Chapter 12: Working with Symbolic Representations 321
Symbolic Differentiation and Expression Rendering 322
Modeling Simple Algebraic Expressions 322
Implementing Local Simplifications 324
A Richer Language of Algebraic Expressions 325
Parsing Algebraic Expressions 327
www.it-ebooks.info
■ CONTENTS

xvi

Simplifying Algebraic Expressions 329
Symbolic Differentiation of Algebraic Expressions 331
Rendering Expressions 332
Building the User Interface 338
Verifying Circuits with Propositional Logic 340
Representing Propositional Logic 341
Evaluating Propositional Logic Naively 342

From Circuits to Propositional Logic 344
Checking Simple Properties of Circuits 347
Representing Propositional Formulae Efficiently Using BDDs 348
Circuit Verification with BDDs 352
Summary 354
■ Chapter 13: Reactive, Asynchronous, and Parallel Programming 355
Introducing Some Terminology 356
Using and Designing Background Workers 357
Building a Simpler Iterative Worker 359
Raising Additional Events from Background Workers 362
Connecting a Background Worker to a GUI 363
Introducing Asynchronous and Parallel Computations 365
Fetching Multiple Web Pages in Parallel, Asynchronously 365
Understanding Thread Hopping 367
Under the Hood: What Are Asynchronous Computations? 368
Parallel File Processing Using Asynchronous Workflows 370
Running Asynchronous Computations 374
Common I/O Operations in Asynchronous Workflows 374
Under the Hood: Implementing Async.Parallel 375
Using async for CPU Parallelism with Fixed Tasks 376
Understanding Exceptions and Cancellation 376
Passing and Processing Messages 377
Introducing Message Processing 378
Creating Objects That React to Messages 379
Scanning Mailboxes for Relevant Messages 382
www.it-ebooks.info
■ CONTENTS

xvii


Example: Asynchronous Web Crawling 383
Using Shared-Memory Concurrency 385
Creating Threads Explicitly 386
Shared Memory, Race Conditions, and the .NET Memory Model 386
Using Locks to Avoid Race Conditions 387
Using ReaderWriterLock 388
Some Other Concurrency Primitives 389
Summary 389
■ Chapter 14: Building Smart Web Applications 391
Serving Static Web Content 391
Serving Dynamic Web Content with ASP.NET 395
Understanding the Languages Used in ASP.NET 397
A Simple ASP.NET Web Application 399
Deploying and Running the Application 402
Using Code-Behind Files 404
Using ASP.NET Input Controls 405
Displaying Data from Databases 408
Going Further with ASP.NET 412
ASP.NET Directives 412
Server Controls 413
Debugging, Profiling, and Tracing 415
Understanding the ASP.NET Event Model 416
Maintaining the View State 418
Understanding the Provider Model 419
Creating Custom ASP.NET Server Controls 420
Building Ajax Rich Client Applications 422
More on the WebSharper Platform 422
Using WSDL Web Services 430
Consuming Web Services 430
Calling Web Services Asynchronously 433

Summary 434
www.it-ebooks.info
■ CONTENTS

xviii

■ Chapter 15: Working with Data 435
Querying In-Memory Data Structures 435
Select/Where/From Queries Using Aggregate Operators 436
Using Aggregate Operators in Queries 436
Accumulating Using Folding Operators 437
Expressing Some Queries Using Sequence Expressions 438
Using Databases to Manage Data 439
Choosing Your Database Engine 441
Understanding ADO.NET 442
Establishing Connections to a Database Engine 443
Creating a Database 443
Creating Tables and Inserting and Fetching Records 445
Using Untyped Datasets 447
Generating Typed Datasets Using xsd.exe 449
Using Stored Procedures 451
Using Data Grids 452
Working with Databases in Visual Studio 452
Creating a Database 452
Visual Data Modeling: Adding Relationships 453
Accessing Relational Data with Linq Queries 455
Generating the Object/Relational Mapping 455
Building the DataContext Instance 456
Using LINQ from F# 456
Working with XML as a Generic Data Format 458

Constructing XML via LINQ 459
Storing, Loading, and Traversing LinqToXml Documents 460
Querying XML 461
Summary 461
■ Chapter 16: Lexing and Parsing 463
Processing Line-Based Input 464
On-Demand Reading of Files 465
Using Regular Expressions 465
www.it-ebooks.info
■ CONTENTS

xix

Tokenizing with FsLex 466
The FsLex Input in More Detail 469
Generating a Simple Token Stream 470
Tracking Position Information Correctly 472
Handling Comments and Strings 473
Recursive-Descent Parsing 474
Limitations of Recursive-Descent Parsers 478
Parsing with FsYacc 479
The Lexer for Kitty 480
The Parser for Kitty 481
Parsing Lists 483
Resolving Conflicts, Operator Precedence, and Associativity 483
Putting It Together 484
Binary Parsing and Pickling Using Combinators 486
Summary 489
■ Chapter 17: Interoperating with C and COM 491
Common Language Runtime 491

Memory Management at Runtime 493
COM Interoperability 495
Platform Invoke 507
Getting Started with PInvoke 509
Data Structures 510
Marshalling Strings 513
Function Pointers 516
PInvoke Memory Mapping 517
Wrapper Generation and Limits of PInvoke 520
Summary 521
■ Chapter 18: Debugging and Testing F# Programs 523
Debugging F# Programs 524
Using Advanced Features of the Visual Studio Debugger 526
Instrumenting Your Program with the System.Diagnostics Namespace 528
www.it-ebooks.info
■ CONTENTS

xx

Debugging Concurrent and Graphical Applications 531
Debugging and Testing with F# Interactive 533
Controlling F# Interactive 534
Some Common F# Interactive Directives 535
Understanding How F# Interactive Compiles Code 535
F# Interactive and Visual Studio 537
Unit Testing 538
Summary 543
■ Chapter 19: Designing F# Libraries 545
Designing Vanilla .NET Libraries 546
Understanding Functional Design Methodology 550

Applying the .NET Library Design Guidelines to F# 553
Some Recommended Coding Idioms 560
Summary 561
■ Appendix: F# Brief Language Guide 563

Index 571


www.it-ebooks.info
■ CONTENTS

xxi

Foreword
According to Wikipedia, “Scientists include theoreticians who mainly develop new models to explain
existing data and experimentalists who mainly test models by making measurements—though in
practice the division between these activities is not clear-cut, and many scientists perform both.” The
domain-specific language that many scientists use to define their models is mathematics, and since the
early days of computing science, the holy grail has been to close the semantic gap between scientific
models and executable code as much as possible. It is becoming increasingly clear that all scientists are
practicing applied mathematics, and some scientists, such as theoretical physicists, are behaviorally
indistinguishable from pure mathematicians. The more we can make programming look like
mathematics, the more helpful we make it to scientists and engineers.
John Backus wrote the design for the “IBM Mathematical Formula Translating System,” which
later became the language FORTAN, in the early 1950s. Still today, FORTRAN is popular within the
scientific community for writing efficient numeric computations. The second oldest programming
language, Lisp, was invented by John McCarthy in 1958. Like FORTRAN, Lisp was also inspired by
mathematics, in this case by Alonzo Church’s lambda calculus. Today, Lisp is still popular in the
scientific community for writing high-level symbolic computations.
Interestingly, despite their common roots in mathematics, one can consider FORTRAN as the

mother of all imperative and object-oriented languages and Lisp as the mother of all declarative
languages. Their differences can be accounted to point of view: FORTRAN starts close to the machine
with numbers and moves upward toward the mathematics, adding layers of abstraction where possible.
Lisp starts with the mathematics with symbols and grows downward to the machine, peeling off layers of
abstraction when necessary. But just as the previous quote remarks that the division between theoretical
and experimental scientists is not clear-cut, in practice many programming problems require both
imperative and declarative aspects.
Functional programming today is a close-kept secret amongst researchers, hackers, and elite
programmers at banks and financial institutions, chip designers, graphic artists, and architects. As the
grandchildren of Lisp, functional programming languages allow developers to write concise programs
that are extremely close to the mathematical models they develop to understand the universe, the
human genome, the pricing of options, the location of oil, the serving of advertisements on web pages,
or the writing of fault-tolerant distributed systems. However, to the uninformed developer, functional
programming seems a cruel and unnatural act, effete mumbo jumbo. The academic and mathematical
origins of functional programming plays up in scary big words such as type inference, structural types,
closures, currying, continuations, principal types, monads, inference, impredicative higher-ranked types,
and so on. Even worse, most pure functional languages today are not well integrated with mainstream
professional tools and IDEs, libraries, and frameworks.
Imperative programming today is the tool of choice for scientific programmers who simulate
fluid dynamics, chemical reactions, mechanical models, and commercial software developers who write
operating systems, enterprise applications, and shrink-wrapped software such as word processors,
spreadsheets, games, media players, and so on. Imperative languages typically have great tool support,
debuggers, profilers, refactoring editors, unit test frameworks, and so on, and large standard numeric
libraries that have been perfected over decades by domain experts. As grandchildren of FORTRAN, they
focus on machine operations first and build abstractions upward. Compared to functional languages,
their syntax is unnecessarily verbose, and they lack m
odern features emerging from the mathematics of
computing itself, such as closures, type inference, anonymous and structural types, and pattern
www.it-ebooks.info
■ FOREWORD


xxii

matching. These features are essential for the kind of compositional development that makes functional
programming so powerful.
F# is unique amongst both imperative and declarative languages in that it is the golden middle
road where these two extremes converge. F# takes the best features of both paradigms and tastefully
combines them in a highly productive and elegant language that both scientists and developers identify
with. F# makes programmers better mathematicians and mathematicians better programmers.

Erik Meijer
www.it-ebooks.info
■ CONTENTS

xxiii

About the Authors
■ DON SYME is a Principal Researcher at Microsoft Research, and the main designer of F#. Since
joining Microsoft Research in 1998, he has been a seminal contributor to a wide variety of leading-edge
projects, including generics in C# and the .NET Common Language Runtime, F# itself, F# asynchronous
programming and Units of Measure in F#. He received a Ph.D. from the University of Cambridge
Computer Laboratory in 1999.

■ ADAM GRANICZ is the CEO of IntelliFactory, the leading provider of F# training, development and
consulting services, and technologies that enable rapid functional, reactive web development. He has
over six years of experience applying F# in commercial projects, and works on WebSharper,
IntelliFactory's web development platform that offers unrivaled productivity, a uniform programming
model based on F#, and the fastest way to develop robust, client-based Rich Internet Applications.
Adam is an active F# evangelist, a regular author in online F# media and speaker at development
conferences and industry partners, and serves on the steering committee of the Commercial Users of

Functional Programming (CUFP) Workshop, representing the F# segment.
■ ANTONIO CISTERNINO is assistant professor in the Computer Science Department of the University
of Pisa. His primary research is on meta-programming and domain-specific languages on virtual-
machine-based execution environments. He has been active in the .NET community since 2001, he
recently developed VSLab, a Visual Studio add-in designed to add the ability of creating dynamic tool-
windows, and he also contributed to the development of Octopus, a scheduler of virtual machines
running on Hyper-V. He teaches F# in the Programming Graphical Interfaces course at the University of
Pisa. Antonio has a Ph.D. in Computer Science from the University of Pisa.
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×