The Definitive Guide To F# 2.0

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

The Definitive Guide to F# is about practical programming in a beautiful language that puts the power and elegance of functional programming into the hands of professional developers. In combination with .NET, F# achieves unrivaled levels of programmer productivity and program clarity.

The Definitive Guide to F# is

The authoritative guide to F# by the inventor of F# A comprehensive reference of F# concepts, syntax, and features A treasury of expert F# techniques for practical, real-world programming

F# isn't just another functional programming language. It's a general-purpose language ideal for real-world development. F# seamlessly integrates functional, imperative, and object-oriented programming styles so you can flexibly and elegantly solve any programming problem. Whatever your background, you’ll find that F# is easy to learn, fun to use, and extraordinarily powerful. F# will change the way you think about–and go about–programming.

Written by F#'s inventor and two major contributors to its development, The Definitive Guide to F# is the authoritative, comprehensive, and in-depth guide to the language and its use. Designed to help others become experts, the first part of the book quickly yet carefully describes the F# language. The second part then shows how to use F# elegantly for a wide variety of practical programming tasks.

The world's foremost experts in F# show you how to program in F# the way they do!

What you'll learn Explore F# and its features quickly and thoroughly in the introductory chapters Use F# with the newest .NET technologies such as WPF, LINQ, and ASP.NET AJAX Build reactive, asynchronous, and distributed applications with F# Interoperate with F# from other .NET languages, especially C# Test, profile, and performance tune F# applications Work with real-life examples and advanced programming features Who is this book for?

The Definitive Guide to F# is for anyone interested in state-of-the art .NET programming. Professional programmers will find it engrossing. F# provides invaluable insight into the future of both C# and VB, which are now adopting some (but far from all) of the functional features of F#. Once programmers learn F#, few feel like returning to either C# or VB. The academic community will find F# the answer to a decades-long prayer: a language suitable for teaching computer science that also excites and empowers students because it can be used not just in the classroom, but also in the real world.

Author(s): Don Syme; Adam Granicz; Antonio Cisternino
Year: 2010

Language: English

Prelim
Contents at a Glance
Contents
Foreword
About the Authors
About the Technical Reviewer
Acknowledgments
Introduction
The Genesis of F#
About This Book
Who This Book Is For
Getting Started with F# and .NET
Creating Your First F# Program
Documenting Code Using XMLDocs
Using let
Understanding Types
Calling Functions
Lightweight Syntax
Understanding Scope
Using Data Structures
Using Properties and the Dot-Notation
Using Tuples
Using Imperative Code
Using .NET Libraries from F#
Using open to Access Namespaces and Modules
Using new and Setting Properties
Fetching a Web Page
Summary
Creating Your First F# Program— Introducing Functional Programming
Getting Started with F# Arithmetic
Basic Literals
Arithmetic Operators
Bitwise Operations
Arithmetic Conversions
Arithmetic Comparisons
Overloaded Math Functions
Introducing Simple Strings
Working with String Literals and Primitives
Building Strings
Working with Lists and Options
Using F# Lists
Using F# Option Values
Using Option Values for Control
Working with Conditionals: && and ||
Defining Recursive Functions
Introducing Function Values
Using Anonymous Function Values
Computing with Aggregate Operators
Composing Functions with >>
Building Functions with Partial Application
Using Local Functions
Using Functions as Abstract Values
Iterating with Aggregate Operators
Abstracting Control with Functions
Using .NET Methods as First-Class Functions
Getting Started with Pattern Matching
Matching on Structured Values
Guarding Rules and Combining Patterns
Getting Started with Sequences
Using Range Expressions
Iterating a Sequence
Transforming Sequences with Aggregate Operators
Which Types Can Be Used as Sequences?
Using Lazy Sequences from External Sources
Using Sequence Expressions
Creating Sequence Expressions Using for
Enriching Sequence Expressions with Additional Logic
Generating Lists and Arrays Using Sequence Expressions
Exploring Some Simple Type Definitions
Defining Type Abbreviations
Defining Records
Handling Non-Unique Record Field Names
Cloning Records
Defining Discriminated Unions
Using Discriminated Unions as Records
Defining Multiple Types Simultaneously
Summary
Introducing Imperative Programming
Imperative Looping and Iterating
Simple for Loops
Simple while Loops
More Iteration Loops over Sequences
Using Mutable Records
Mutable Reference Cells
Avoiding Aliasing
Hiding Mutable Data
Using Mutable Locals
Working with Arrays
Generating and Slicing Arrays
Two-Dimensional Arrays
Introducing the Imperative .NET Collections
Using Resizeable Arrays
Using Dictionaries
Using Dictionary’s TryGetValue
Using Dictionaries with Compound Keys
Some Other Mutable Data Structures
Exceptions and Controlling Them
Catching Exceptions
Using try . . . finally
Defining New Exception Types
Having an Effect: Basic I/O
Very Simple I/O: Reading and Writing Files
.NET I/O via Streams
Some Other I/O-Related Types
Using System.Console
Using printf and Friends
Generic Structural Formatting
Cleaning Up with IDisposable, use, and using
Working with null Values
Some Advice: Functional Programming with Side Effects
Consider Replacing Mutable Locals and Loops with Recursion
Separate Pure Computation from Side-Effecting Computations
Separate Mutable Data Structures
Not All Side Effects Are Equal
Avoid Combining Imperative Programming and Laziness
Summary
Mastering Types and Generics
Understanding Generic Type Variables
Writing Generic Functions
Understanding Some Important Generic Functions
Generic Comparison
Generic Hashing
Generic Pretty-Printing
Generic Boxing and Unboxing
Generic Binary Serialization via the .NET Libraries
Making Things Generic
Generic Algorithms through Explicit Arguments
Generic Algorithms through Abstract Object Types
Arithmetic Operators and Generic Algorithms through Inlining
Understanding .NET Types
Reference Types and Value Types
Other Flavors of .NET Types
Understanding Subtyping
Casting Up Statically
Casting Down Dynamically
Performing Type Tests via Pattern Matching
Knowing When Upcasts Are Applied Automatically
Flexible Types
Units of Measure
Troubleshooting Type-Inference Problems
Using a Visual Editing Environment
Using Type Annotations
Understanding the Value Restriction
Working Around the Value Restriction
Technique 1: Constrain Values to Be Nongeneric
Technique 2: Ensure Generic Functions Have Explicit Arguments
Technique 3: Add Dummy Arguments to Generic Functions When Necessary
Technique 4: Add Explicit Type Arguments When Necessary
Understanding Generic Overloaded Operators
Summary
Working with Objects and Modules
Getting Started with Objects and Members
Using Classes
Adding Further Object Notation to Your Types
Working with Indexer Properties
Adding Overloaded Operators
Using Named and Optional Arguments
Using Optional Property Settings
Adding Method Overloading
Defining Object Types with Mutable State
Getting Started with Object Interface Types
Defining New Object Interface Types
Implementing Object Interface Types Using Object Expressions
Implementing Object Interface Types Using Concrete Types
Using Common Object Interface Types from the .NET Libraries
Understanding Hierarchies of Object Interface Types
More Techniques to Implement Objects
Combining Object Expressions and Function Parameters
Defining Partially Implemented Class Types
Using Partially Implemented Types via Delegation
Using Partially Implemented Types via Implementation Inheritance
Using Modules and Static Members
Extending Existing Types and Modules
Working with F# Objects and .NET Types
Structs
Delegates
Enums
Summary
Encapsulating and Packaging Your Code
Hiding Things Away
Hiding Things with Local Definitions
Hiding Things with Accessibility Annotations
Using Namespaces and Modules
Putting Your Code in a Namespace
Using Files as Modules
Creating Assemblies, DLLs, and EXEs
Compiling EXEs
Compiling DLLs
Mixing Scripting and Compiled Code
Choosing Optimization Settings
Generating Documentation
Building Shared Libraries and Using the Global Assembly Cache
Using Static Linking
Using Signature Types and Files
Using Explicit Signature Types and Signature Files
When Are Signature Types Checked?
Packaging Applications
Packaging Different Kinds of Code
Using Data and Configuration Settings
Summary
Mastering F#: Common Techniques
Equality, Hashing, and Comparison
Asserting Equality, Hashing, and Comparison Using Attributes
Fully Customizing Equality, Hashing, and Comparison on a Type
Suppressing Equality, Hashing, and Comparison on a Type
Customizing Generic Collection Types
Efficient Precomputation and Caching
Precomputation and Partial Application
Precomputation and Objects
Memoizing Computations
Lazy Values
Other Variations on Caching and Memoization
Cleaning Up Resources
Cleaning Up with use
Managing Resources with More Complex Lifetimes
Cleaning Up Internal Objects
Cleaning Up Unmanaged Objects
Cleaning Up in Sequence Expressions
Using using
Stack as a Resource: Tail Calls and Recursion
Tail Recursion and List Processing
Tail Recursion and Object-Oriented Programming
Tail Recursion and Processing Unbalanced Trees
Using Continuations to Avoid Stack Overflows
Another Example: Processing Syntax Trees
Events
Events as First-Class Values
Creating and Publishing Events
Summary
Introducing Language-Oriented Programming
Using XML as a Concrete Language Format
Using the System.Xml Namespace
From Concrete XML to Abstract Syntax
Working with Abstract Syntax Representations
Abstract Syntax Representations: Less Is More
Processing Abstract Syntax Representations
Transformational Traversals of Abstract Syntax Representations
Using On-Demand Computation with Abstract Syntax Trees
Caching Properties in Abstract Syntax Trees
Memoizing Construction of Syntax Tree Nodes
Introducing Active Patterns
Converting the Same Data to Many Views
Matching on .NET Object Types
Defining Partial and Parameterized Active Patterns
Hiding Abstract Syntax Implementations with Active Patterns
Embedded Computational Languages with Workflows
An Example: Success/Failure Workflows
Defining a Workflow Builder
Workflows and Untamed Side Effects
Example: Probabilistic Workflows
Combining Workflows and Resources
Recursive Workflow Expressions
Using F# Reflection
Reflecting on Types
Schema Compilation by Reflecting on Types
Using the F# Dynamic Reflection Operators
Using F# Quotations
Example: Using F# Quotations for Error Estimation
Resolving Top Definitions
Summary
Using the F# and .NET Libraries
A High-Level Overview
Namespaces from the .NET Framework
Namespaces from the F# Libraries
Using the System Types
Using Regular Expressions and Formatting
Matching with System.Text.RegularExpressions
Formatting Strings Using .NET Formatting
Encoding and Decoding Unicode Strings
Encoding and Decoding Binary Data
Using Further F# and .NET Data Structures
System.Collections.Generic and Other .NET Collections
Introducing Microsoft.FSharp.Math
Using Matrices and Vectors
Using Operator Overloads on Matrices and Vectors
Supervising and Isolating Execution
Further Libraries for Reflective Techniques
Using General Types
Using Microsoft.FSharp.Reflection
Some Other .NET Types You May Encounter
Some Other .NET Libraries
Summary
Building Graphical User Interfaces
Writing “Hello, World!” in a Click
Understanding the Anatomy of a Graphical Application
Composing User Interfaces
Drawing Applications
Writing Your Own Controls
Developing a Custom Control
Anatomy of a Control
Displaying Samples from Sensors
Building the GraphControl: The Model
Building the GraphControl: Style Properties and Controller
Building the GraphControl: The View
Putting It Together
Creating a Mandelbrot Viewer
Computing Mandelbrot
Setting Colors
Creating the Visualization Application
Creating the Application Plumbing
Windows Presentation Foundation
When GUIs Meet the Web
Drawing
Controls
Bitmaps and Images
Final Considerations
Summary
Working with Symbolic Representations
Symbolic Differentiation and Expression Rendering
Modeling Simple Algebraic Expressions
Implementing Local Simplifications
A Richer Language of Algebraic Expressions
Parsing Algebraic Expressions
Simplifying Algebraic Expressions
Symbolic Differentiation of Algebraic Expressions
Rendering Expressions
Converting to VisualExpr
Rendering
Building the User Interface
Verifying Circuits with Propositional Logic
Representing Propositional Logic
Evaluating Propositional Logic Naively
From Circuits to Propositional Logic
Checking Simple Properties of Circuits
Representing Propositional Formulae Efficiently Using BDDs
Circuit Verification with BDDs
Summary
Reactive, Asynchronous, and Parallel Programming
Introducing Some Terminology
Using and Designing Background Workers
Building a Simpler Iterative Worker
Raising Additional Events from Background Workers
Connecting a Background Worker to a GUI
Introducing Asynchronous and Parallel Computations
Fetching Multiple Web Pages in Parallel, Asynchronously
Understanding Thread Hopping
Under the Hood: What Are Asynchronous Computations?
Parallel File Processing Using Asynchronous Workflows
Running Asynchronous Computations
Common I/O Operations in Asynchronous Workflows
Under the Hood: Implementing Async.Parallel
Using async for CPU Parallelism with Fixed Tasks
Understanding Exceptions and Cancellation
Passing and Processing Messages
Introducing Message Processing
Creating Objects That React to Messages
Scanning Mailboxes for Relevant Messages
Example: Asynchronous Web Crawling
Using Shared-Memory Concurrency
Creating Threads Explicitly
Shared Memory, Race Conditions, and the .NET Memory Model
Using Locks to Avoid Race Conditions
Using ReaderWriterLock
Some Other Concurrency Primitives
Summary
Building Smart Web Applications
Serving Static Web Content
Serving Dynamic Web Content with ASP.NET
Understanding the Languages Used in ASP.NET
A Simple ASP.NET Web Application
Deploying and Running the Application
Using Code-Behind Files
Using ASP.NET Input Controls
Displaying Data from Databases
Going Further with ASP.NET
ASP.NET Directives
Server Controls
Debugging, Profiling, and Tracing
Understanding the ASP.NET Event Model
Maintaining the View State
Understanding the Provider Model
Configuring the Provider Database
Creating Custom ASP.NET Server Controls
Building Ajax Rich Client Applications
More on the WebSharper Platform
Getting Started with WebSharper
WebSharper Pagelets
Calling Server Code from the Client
WebSharper Formlets
.NET Proxies and JavaScript Stubs
Automated Resource Tracking and Handling
Dependent Formlets and Flowlets
Using WSDL Web Services
Consuming Web Services
Calling Web Services Asynchronously
Summary
Working with Data
Querying In-Memory Data Structures
Select/Where/From Queries Using Aggregate Operators
Using Aggregate Operators in Queries
Accumulating Using Folding Operators
Expressing Some Queries Using Sequence Expressions
Using Databases to Manage Data
Choosing Your Database Engine
Understanding ADO.NET
Establishing Connections to a Database Engine
Creating a Database
Creating Tables and Inserting and Fetching Records
Using Untyped Datasets
Generating Typed Datasets Using xsd.exe
Using Stored Procedures
Using Data Grids
Working with Databases in Visual Studio
Creating a Database
Visual Data Modeling: Adding Relationships
Accessing Relational Data with Linq Queries
Generating the Object/Relational Mapping
Building the DataContext Instance
Using LINQ from F#
Working with XML as a Generic Data Format
Constructing XML via LINQ
Storing, Loading, and Traversing LinqToXml Documents
Querying XML
Summary
Lexing and Parsing
Processing Line-Based Input
On-Demand Reading of Files
Using Regular Expressions
Tokenizing with FsLex
The FsLex Input in More Detail
Generating a Simple Token Stream
Tracking Position Information Correctly
Handling Comments and Strings
Recursive-Descent Parsing
Limitations of Recursive-Descent Parsers
Parsing with FsYacc
The Lexer for Kitty
The Parser for Kitty
Parsing Lists
Resolving Conflicts, Operator Precedence, and Associativity
Putting It Together
Binary Parsing and Pickling Using Combinators
Summary
Interoperating with C and COM
Common Language Runtime
Memory Management at Runtime
COM Interoperability
Platform Invoke
Getting Started with PInvoke
Data Structures
Marshalling Strings
Function Pointers
PInvoke Memory Mapping
Wrapper Generation and Limits of PInvoke
Summary
Debugging and Testing F# Programs
Debugging F# Programs
Using Advanced Features of the Visual Studio Debugger
Instrumenting Your Program with the System.Diagnostics Namespace
Debugging Concurrent and Graphical Applications
Debugging and Testing with F# Interactive
Controlling F# Interactive
Some Common F# Interactive Directives
Understanding How F# Interactive Compiles Code
F# Interactive and Visual Studio
Unit Testing
Summary
Designing F# Libraries
Designing Vanilla .NET Libraries
Understanding Functional Design Methodology
Applying the .NET Library Design Guidelines to F#
Some Recommended Coding Idioms
Summary
F# Brief Language Guide
Comments and Attributes
Basic Types and Literals
Types
Patterns and Matching
Functions, Composition, and Pipelining
Binding and Control Flow
Exceptions
Tuples, Arrays, Lists, and Collections
Operators
Type Definitions and Objects
Namespaces and Modules
Sequence Expressions and Workflows
Index