1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Expert F 3 0 3rd edition pot

616 3K 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Cover

    • Contents at a Glance

    • Contents

    • About the Authors

    • About the Technical Reviewer

    • Acknowledgments

  • Chapter 1 Introduction

    • The Genesis of F#

    • About This Book

    • Who This Book Is For

  • Chapter 2 Your First F# Program – Getting Started With F#

    • Creating Your First F# Program

      • Documenting Code

      • 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 Object-Oriented Libraries from F#

      • Using open to Access Namespaces and Modules

      • Using new and Setting Properties

      • Fetching a Web Page

    • Summary

  • Chapter 3 Introducing Functional Programming

    • Starting with Numbers and Strings

      • Some Simple Types and Literals

      • Arithmetic Conversions

      • Arithmetic Comparisons

      • Simple Strings

    • Working with Conditionals: && and ||

    • Defining Recursive Functions

    • Lists

    • Options

    • Getting Started with Pattern Matching

      • Matching on Structured Values

      • Guarding Rules and Combining Patterns

      • Further Ways of Forming Patterns

    • Introducing Function Values

      • Using Anonymous Function Values

      • Computing with Aggregate Operators

      • Composing Functions with >>

      • Building Functions with Partial Application

      • Using Local Functions

      • Iterating with Aggregate Operators

      • Abstracting Control with Functions

      • Using Object Methods as First-Class Functions

      • Some Common Uses of Function Values

    • Summary

  • Chapter 4 Introducing Imperative Programming

    • About Functional and 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

      • .NET I/O via Streams

      • Some Other I/O-Related Types

      • Using System.Console

    • Combining Functional and Imperative: Efficient Precomputation and Caching

      • Precomputation and Partial Application

      • Precomputation and Objects

      • Memoizing Computations

      • Lazy Values

      • Other Variations on Caching and Memoization

    • Combining Functional and Imperative: Functional Programming with Side Effects

      • Consider Replacing Mutable Locals and Loops with Recursion

      • Separating Pure Computation from Side-Effecting Computations

      • Separating Mutable Data Structures

      • Not All Side Effects Are Equal

      • Avoid Combining Imperative Programming and Laziness

    • Summary

  • Chapter 5 Understanding Types in Functional Programming

    • Exploring Some Simple Type Definitions

      • Defining Type Abbreviations

      • Defining Record Types

      • Handling Non-Unique Record Field Names

      • Cloning Records

      • Defining Discriminated Unions

      • Using Discriminated Unions as Records

      • Defining Multiple Types Simultaneously

    • Understanding Generics

      • Writing Generic Functions

      • Some Important Generic Functions

    • Making Things Generic

      • Generic Algorithms through Explicit Arguments

      • Generic Algorithms through Function Parameters

      • Generic Algorithms through Inlining

    • More on Different Kinds of 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

    • Troubleshooting Type-Inference Problems

      • Using a Visual Editing Environment

      • Using Type Annotations

      • Understanding the Value Restriction

      • Working Around the Value Restriction

      • Understanding Generic Overloaded Operators

    • Summary

  • Chapter 6 Programming with Objects

    • 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

      • Adding Method Overloading

    • Defining Object Types with Mutable State

      • Using Optional Property Settings

      • Declaring Auto-Properties

    • 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

    • Combining Functional and Objects: Cleaning Up Resources

      • Resources and IDisposable

      • Managing Resources with More Complex Lifetimes

      • Cleaning Up Internal Objects

      • Cleaning Up Unmanaged Objects

    • Extending Existing Types and Modules

    • Working with F# Objects and .NET Types

      • Structs

      • Delegates

      • Enums

      • Working with null Values

    • Summary

  • Chapter 7 Encapsulating and Organizing Your Code

    • Hiding Things

      • Hiding Things with Local Definitions

      • Hiding Things with Accessibility Annotations

    • Organizing Code with Namespaces and Modules

      • Putting Your Modules and Types in Namespaces

      • Hiding Things with Signatures

      • Designing with Signatures

      • When Are Signature Types Checked?

      • Defining a Module with the Same Name as a Type

      • Preventing Client Code from Opening a Module

      • Using Files as Modules

      • Automatically Opening Modules

    • Reusing Your Code

      • Using Files as Small Reusable Components

      • Creating Assemblies, DLLs, and EXEs

      • Creating and Sharing Packages

    • Summary

  • Chapter 8 Working with Textual Data

    • Building Strings and Formatting Data

      • Building Strings

      • More about String Literals

      • Generic Structural Formatting

      • Formatting Strings Using .NET Formatting

    • Parsing Strings and Textual Data

      • Parsing Basic Values

      • Processing Line-Based Input

      • Using Regular Expressions to Parse Lines

      • More on Matching with System.Text.RegularExpressions

      • Encoding and Decoding Unicode Strings

    • Using XML as a Concrete Language Format

      • Using the System.Xml Namespace

    • Some Recursive Descent Parsing

      • A Simple Tokenizer

      • Recursive-Descent Parsing

    • Binary Parsing and Formatting

    • Summary

  • Chapter 9 Working with Sequences and Structured Data

    • 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

      • Enriching Sequence Expressions with Additional Logic

      • Generating Lists and Arrays Using Sequence Expressions

    • More on Working with Sequences

      • Using Other Sequence Operators: Truncate and Sort

      • Selecting Multiple Elements From Sequences

      • Finding Elements and Indexes in Sequences

      • Grouping and Indexing Sequences

      • Folding Sequences

      • Cleaning Up in Sequence Expressions

      • Expressing Some Operations Using Sequence Expressions

    • Structure Beyond Sequences: Working with Trees

      • Example: Abstract Syntax Representations

      • Transforming Abstract Syntax Representations

      • Using On-Demand Computation with Abstract Syntax Trees

      • Caching Properties in Abstract Syntax Trees

      • Memoizing Construction of Syntax Tree Nodes

    • Active Patterns: Views for Structured Data

      • 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

    • Equality, Hashing, and Comparison for New Structured Data Types

      • 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

    • Tail Calls and Recursive Programming

      • 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

    • Summary

  • Chapter 10 Numeric Programming and Charting

    • Basic Charting with FSharpChart

    • Basic Numeric Types and Literals

      • Arithmetic Operators

      • Checked Arithmetic

      • Arithmetic Conversions

      • Arithmetic Comparisons

      • Overloaded Math Functions

      • Bitwise Operations

    • Sequences, Statistics and Numeric Code

      • Summing, Averaging, Maximizing and Minimizing Sequences

      • Counting and Categorizing

      • Writing Fresh Numeric Code

      • Making Numeric Code Generic

      • Example: KMeans

    • Statistics, Linear Algebra and Distributions with Math.NET

      • Basic Statistical Functions in Math.NET Numerics

      • Using Histograms and Distributions from Math.NET Numerics

      • Using Matrices and Vectors from Math.NET

      • Matrix Inverses, Decompositions and Eigenvalues

    • Units of Measure

      • Adding Units to a Numeric Algorithms

      • Adding Units to a Type Definition

      • Applying and Removing Units

      • Some Limitations of Units of Measure

    • Summary

  • Chapter 11 Reactive, Asynchronous, and Parallel Programming

    • Introducing Some Terminology

    • Events

      • Events as First-Class Values

      • Creating and Publishing Events

    • 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

      • Using Tasks with Asynchronous Programming

      • Understanding Exceptions and Cancellation

      • Under the Hood: Implementing Async.Parallel

      • Using async for CPU Parallelism with Fixed Tasks

    • Agents

      • Introducing Agents

      • Creating Objects That React to Messages

      • Scanning Mailboxes for Relevant Messages

      • Example: Asynchronous Web Crawling

    • Observables

    • 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

  • Chapter 12 Symbolic Programming with Structured Data

    • 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

    • 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

      • Building the User Interface

    • Summary

  • Chapter 13 Integrating External Data and Services

    • Some Basic REST Requests

      • Getting Data in JSON Format

      • Parsing the XML or JSON Data

      • Handling Multiple Pages

    • Getting Started with Type Providers and Queries

      • Example Language Integrated OData

      • What is a Type Provider?

      • What is a Query?

      • Handling Pagination in OData

      • Example Language Integrated SQL

    • More on Queries

      • Sorting

      • Aggregation

      • Nullables

      • Inner Queries

      • Grouping

      • Joins

    • More on Relational Databases and ADO.NET

      • Establishing Connections using ADO.NET

      • Creating a Database using ADO.NET

      • Creating Tables using ADO.NET

      • Using Stored Procedures via ADO.NET

    • Using WSDL Services

    • Summary

  • Chapter 14 Building Smart Web Applications

    • Serving Web Content the Simple Way

    • Building Ajax Rich Client Applications

      • Learning More from the WebSharper Documentation

      • Getting Started with WebSharper

      • WebSharper Pagelets

      • Calling Server Code from the Client

      • WebSharper Sitelets

      • Online vs. Offline Sitelets

      • Serving Content from WebSharper Sitelets

      • Using Dynamic Templates

      • Embedding Client-Side Controls in Sitelet Pages

      • Constructing and Combining Sitelets

      • Sitelet Routers and Controllers

      • Constructing Sitelets for Handling Non-GET HTTP Commands

      • WebSharper Formlets

      • Dependent Formlets and Flowlets

      • Automated Resource Tracking and Handling

      • Using Third-Party JavaScript Libraries

      • Working with .NET Proxies

    • Summary

  • Chapter 15 Building Mobile Web Applications

    • Web-based vs. Native Mobile Applications

    • Feature Detection and Polyfilling in WebSharper

    • Mobile Capabilities, Touch Events, and Mobile Frameworks

    • Serving Mobile Content

    • Building a Mobile Web Application for iOS Devices

      • Fleshing Out the Application

      • Digging Deeper

    • Developing Social Networking Applications

      • Configuring Your New Facebook Application

      • Defining the Main HTML Application

    • WebSharper Mobile

    • Developing Android Applications with WebSharper

      • Setting Up and Testing with Your Android Environment

      • Using the Android Application Visual Studio Template

      • Implementing Your Native Android Application

    • Summary

  • Chapter 16 Visualization and 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

  • Chapter 17 Language-Oriented Programming: Advanced Techniques

    • Computation Expressions

      • An Example: Success/Failure Workflows

      • Defining a Workflow Builder

      • Workflows and Untamed Side Effects

      • Computation Expressions with Custom Query Operators

      • 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 Reflected Definitions

    • Summary

  • Chapter 18 Libraries and Interoperating with Other Languages

    • Types, memory and interoperability

    • Libraries: A High-Level Overview

      • Namespaces from the .NET Framework

      • Namespaces from the F# Libraries

    • Using the System Types

    • Using Further F# and .NET Data Structures

      • System.Collections.Generic and Other .NET Collections

    • Supervising and Isolating Execution

    • Further Libraries for Reflective Techniques

      • Using General Types

      • Using Microsoft.FSharp.Reflection

    • Some Other .NET Types You May Encounter

    • Under the Hood: Interoperating with C# and other .NET Languages

      • The Common Language Runtime

      • Memory Management at Runtime

    • COM Interoperability

      • Calling COM Components from F#

      • The Running Object Table

    • Interoperating with C and C++ with PInvoke

      • Getting Started with PInvoke

      • Mapping C Data Structures to F# Code

      • Marshalling Parameters to and from C

      • Marshalling Strings to and from C

      • Passing Function Pointers to C

      • PInvoke Memory Mapping

      • Wrapper Generation and Limits of PInvoke

    • Summary

  • Chapter 19 Packaging, Debugging and Testing F# Code

    • Packaging Your Code

      • Mixing Scripting and Compiled Code

      • Choosing Optimization Settings

      • Generating Documentation

      • Building Shared Libraries

      • Using Static Linking

      • Packaging Different Kinds of Code

      • Using Data and Configuration Settings

    • Debugging Your Code

      • Using More 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

    • Testing Your Code

    • Summary

  • Chapter 20 Designing F# Libraries

    • Designing Vanilla .NET Libraries

    • Understanding Functional Design Methodology

      • Understanding Where Functional Programming Comes From

      • Understanding Functional Design Methodology

    • Applying the .NET Library Design Guidelines to F#

      • Recommendation: Use the .NET Naming and Capitalization Conventions Where Possible

      • Recommendation: Avoid Using Underscores in Names

      • Recommendation: Follow the .NET Guidelines for Exceptions

      • Recommendation: Consider Using Option Values for Return Types Instead of Raising Exceptions

      • Recommendation: Follow the .NET Guidelines for Value Types

      • Recommendation: Consider Using Explicit Signature Files for Your Framework

      • Recommendation: Consider Avoiding the Use of Implementation Inheritance for Extensibility

      • Recommendation: Use Properties and Methods for Attributes and Operations Essential to a Type

      • Recommendation: Avoid Revealing Concrete Data Representations Such as Records

      • Recommendation: Use Active Patterns to Hide the Implementations of Discriminated Unions

      • Recommendation: Use Object Interface Types Instead of Tuples or Records of Functions

      • Recommendation: Understand When Currying Is Useful in Functional Programming APIs

      • Recommendation: Use Tuples for Return Values, Arguments, and Intermediate Values

    • Some Recommended Coding Idioms

      • Recommendation: Use the Standard Operators

      • Recommendation: Place the Pipeline Operator |> at the Start of a Line

      • Recommendation: Format Object Expressions Using the member Syntax

    • Summary

  • Index

Nội dung

www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info iv Contents at a Glance n About the Authors xx n About the Technical Reviewer xxi n Acknowledgments xxii n Chapter 1: Introduction 1 n Chapter 2: Your First F# Program – Getting Started With F# 7 n Chapter 3: Introducing Functional Programming 25 n Chapter 4: Introducing Imperative Programming 49 n Chapter 5: Understanding Types in Functional Programming 81 n Chapter 6: Programming with Objects 111 n Chapter 7: Encapsulating and Organizing Your Code 147 n Chapter 8: Working with Textual Data 163 n Chapter 9: Working with Sequences and Structured Data 189 n Chapter 10: Numeric Programming and Charting 231 n Chapter 11: Reactive, Asynchronous, and Parallel Programming 257 n Chapter 12: Symbolic Programming with Structured Data 295 n Chapter 13: Integrating External Data and Services 331 n Chapter 14: Building Smart Web Applications 353 n Chapter 15: Building Mobile Web Applications 391 n Chapter 16: Visualization and Graphical User Interfaces 427 n Chapter 17: Language-Oriented Programming: Advanced Techniques 477 n Chapter 18: Libraries and Interoperating with Other Languages 503 n Chapter 19: Packaging, Debugging and Testing F# Code 537 n Chapter 20: Designing F# Libraries 565 Index 583 www.it-ebooks.info 1 n n n chapter 1 Introduction F# is a strongly-typed functional programming language designed to empower programmers and domain experts to write simple, robust code to solve complex problems. It combines the succinctness, expressivity, efficiency, and compositionality of typed functional programming with the runtime support, libraries, interoperability, tools, and object models of modern programming frameworks. The aim of this book is to help you become an expert in using F# for a range of practical programming problems. Functional programming has long inspired researchers, students, and programmers alike with its simplicity and expressive power. Applied functional programming is booming: a new generation of typed functional languages is reaching maturity; some functional language constructs have been integrated into languages such as C#, Python, and Visual Basic; and there is now a widespread expertise available in the pragmatic application of functional programming techniques. There is also strong evidence that functional programming offers significant productivity gains in important application areas such as data access, financial modeling, statistical analysis, machine learning, software verification, and bio- informatics. More recently, functional programming is part of the rise of declarative programming models, especially in the data query, concurrent, reactive, and parallel programming domains. F# is a “functional-first” language, where functional programming is the first option used for solving most programming problems. However, F# differs from many functional languages in that it embraces imperative and object-oriented (OO) programming where necessary. It also provides a missing link between compiled and dynamic languages, allowing the idioms and programming styles typical of dynamic languages while preserving the performance and robustness of a strongly-typed compiled language. The F# designers have adopted a design philosophy that allows you to take the best and most productive aspects of these paradigms and combine them while still placing primary emphasis on simple functional programming techniques. This book helps you understand the power that F# offers through this combination. F# offers an approach to computing that will continue to surprise and delight, and mastering functional programming techniques will help you become a better programmer regardless of the language you use. There has been no better time to learn functional programming, and F# offers the best route to learn and apply functional programming to solve real-world problems. Although F# is an open-source language under an OSS-approved license, supported tooling for F# is available from Microsoft through tools such as Visual Studio 2010 and Visual Studio 2012, making functional programming a viable choice for many mainstream and professional programming activities. F# also has a vibrant community, contributing projects for using F# on a wide range of platforms, and contributing an ecosystem of supporting commercial and open-source components and tools. The designer of the F# language, Don Syme, is one of the authors of this book. This book benefits from his authority on F# and .NET and from all the authors’ years of experience with F# and other programming languages. www.it-ebooks.info chapter 1 n IntroductIon 2 The Genesis of F# F# began in 2002, when Don Syme and others at Microsoft Research decided to ensure that the ML approach to pragmatic but theoretically based language design found a high-quality expression for the .NET platform. The project was closely associated with the design and implementation of Generics for the .NET Common Language Runtime. The first stabilized, supported version of F# was F# 2.0, included with Visual Studio 2010. In 2012, Microsoft released F# 3.0. This is the version of the language described in this book and is also the version included with Visual Studio 2012. F# shares a core language with the programming language OCaml, which in turn comes from the ML family of programming languages, which dates back to 1974. F# also draws from Haskell, particularly with regard to two language features: sequence expressions and workflows. Despite the similarities to OCaml and Haskell, programming with F# is quite different in practice. In particular, the F# approach to OO programming, and dynamic language techniques is substantially different from other mainstream functional languages. Programming in F# tends to be more object- oriented than in other functional languages. Programming also tends to be more flexible, as F# embraces techniques such as dynamic loading, dynamic typing, and reflection, and it adds techniques such as expression quotation, units-of-measure, type providers and active patterns. We cover these topics in this book and use them in many application areas. F# also owes a lot to the designers of .NET, whose vision of language interoperability between C++, Visual Basic, and the language that eventually became C# is still shaping the computer industry. Today, F# draws much from the broader community around the Common Language Infrastructure (CLI), implemented by the Microsoft .NET Framework and Mono. F# is able to leverage libraries and techniques developed by Microsoft, the broader .NET community, the highly active open source community centered around Mono, and open source and cross-platform implementation of the ECMA CLI standard that works well on Windows, Mac, and Linux environments. Mono can also be used to author applications for the Android and Apple iOS platforms. F# code can also be edited and executed directly in most web browsers through sites such as www.tryfsharp.org. F# 3.0 can be compiled to Javascript through the open-source community project Pit and the professional open-source product WebSharper, www.websharper.com. About This Book This book is structured in three parts. Chapters 2 to 11 deal with the F# language and basic techniques such as functional, imperative and object-oriented programming, techniques to program with textual, structured and numeric data, and techniques for parallel, reactive and concurrent programming. Chapters 12 to 20 deal with a series of applied programming samples and topics ranging from building applications to software engineering and design issues. Throughout this book, we address both programming constructs and programming techniques. Our approach is driven by examples: we show code, and then we explain it. Frequently, we give reference material describing the constructs used in the code and related constructs you may use in similar programming tasks. We’ve found that an example-driven approach helps bring out the essence of a language and how the language constructs work together. You can find a complete syntax guide in the appendix, and we encourage you to reference it while reading the book. The book’s chapters are as follows, starting with basic F# techniques: Chapter 2, “Your First F# Program – Getting Started With F#,” begins by introducing F# Interactive, a tool you can use to interactively evaluate F# expressions and declarations and that we encourage you to use while reading this book. In this chapter, you use F# Interactive to explore some basic F# and .NET constructs, and we introduce many concepts that are described in more detail in later chapters. www.it-ebooks.info 3 chapter 1 n IntroductIon Chapter 3, “Introducing Functional Programming,” focuses on the basic constructs of typed functional programming, including arithmetic and string primitives, type inference, tuples, lists, options, function values, aggregate operators, recursive functions, function pipelines, function compositions, and pattern matching. Chapter 4, “Introducing Imperative Programming,” introduces the basic constructs used for imperative programming in F#. Although the use of imperative programming is often minimized with F#, it’s used heavily in some programming tasks such as scripting. You learn about loops, arrays, mutability mutable records, locals and reference cells, the imperative .NET collections, exceptions, and the basics of .NET I/O. Chapter 5, “Understanding Types in Functional Programming,”, covers types in more depth, especially the more advanced topics of generic type variables and subtyping. You learn techniques that you can use to make your code generic and how to understand and clarify type error messages reported by the F# compiler. Chapter 6, “Programming with Objects,” introduces object-oriented programming in F#. You learn how to define concrete object types to implement data structures, how to use OO notational devices such as method overloading with your F# types, and how to create objects with mutable state. You then learn how to define object interface types and a range of techniques to implement objects, including object expressions, constructor functions, delegation, and implementation inheritance. Chapter 7, “Encapsulating and Organizing Your Code,” shows the techniques you can use to hide implementation details through encapsulation and to organize your code with namespaces and modules. Chapter 8, “Working with Textual Data,” looks at techniques for formatting data, working with strings, JSON and XML, tokenizing text, parsing text, and marshaling binary values. Chapter 9, “Working with Sequences and Structured Data,” looks at two important sets of functional programming techniques. In this chapter, you learn succinct and compositional techniques for building, transforming, and querying in-memory data structures and sequences. In addition, you learn techniques for working with tree-structured data, especially abstract syntax representations, how to use F# active patterns to hide representations, and how to traverse large structured data without causing stack overflows through the use of tail calls. Chapter 10, “Numeric Programming and Charting,” looks at constructs and libraries for programming with numerical data in F#. In this chapter, you learn about basic numeric types, how to use library routines for summing, aggregating, maximizing and minimizing sequences, how to implement numeric algorithms, how to use the FSharpChart library for charting, how to use units of measure in F# to give strong typing to numeric data, and how to use the powerful open source Math.NET library for advanced vector, matrix, statistical, and linear- algebra programming. www.it-ebooks.info chapter 1 n IntroductIon 4 Chapter 11, “Reactive, Asynchronous, and Parallel Programming,” shows how you can use F# for programs that have multiple logical threads of execution and that react to inputs and messages. You first learn how to construct basic background tasks that support progress reporting and cancellation. You then learn how to use F# asynchronous workflows to build scalable, massively concurrent reactive programs that make good use of the .NET thread pool and other .NET concurrency-related resources. This chapter concentrates on message-passing techniques that avoid or minimize the use of shared memory. However, you also learn the fundamentals of concurrent programming with shared memory using .NET. Chapters 12 to 20 deal with applied topics in F# programming. Chapter 12, “Symbolic Programming with Structured Data,” applies some of the techniques from Chapters 9 and 11 in two case studies. The first is symbolic expression differentiation and rendering, an extended version of a commonly used case study in symbolic programming. The second is verifying circuits with propositional logic; you learn how to use symbolic techniques to represent digital circuits, specify properties of these circuits, and verify these properties using binary decision diagrams (BDDs). Chapter 13, “Integrating External Data and Services,” looks at several dimensions of querying and accessing data from F#. You first learn how to use the type provider feature of F# 3.0 to give fluent data scripting against databases and web services. You then learn how to use queries with F#, in particular the LINQ paradigm supported by .NET. You then look at how to use F# in conjunction with relational databases, particularly through the use of the ADO.NET and LINQ-to- SQL technologies that are part of the .NET Framework. Chapter 14, “Build Smart Web Applications,” shows how to use F# with ASP.NET to write server-side scripts that respond to web requests. You learn how to serve web-page content using ASP.NET controls. We also describe how projects such as the WebSharper Platform let you write HTML5 Web Applications in F#. Chapter 15, “Building Mobile Web Applications,” shows how to use the WebSharper framework to build web applications customized for mobile devices. In this chapter, you learn how you can serve mobile web content from your WebSharper applications, how you can use feature detection and polyfilling libraries in your applications to work around mobile browser limitations and missing features, how you can develop WebSharper applications for iOS that use platform-specific markup to access unique features such as multi-touch events, how you can develop WebSharper applications that use the Facebook API, how you can use WebSharper Mobile to create native Android and Windows Phone packages for your WebSharper applications, and how you can integrate mobile formlets and Bing Maps in a WebSharper application. Chapter 16, “Visualization and Graphical User Interfaces,” shows how to design and build graphical user interface applications using F# and the .NET Windows Forms and WPF libraries. We also show how to design new controls using standard OO design patterns and how to script applications using the controls offered by the .NET libraries directly. www.it-ebooks.info 5 chapter 1 n IntroductIon Chapter 17, “Language-Oriented Programming: Advanced Techniques,” looks at what is effectively a fourth programming paradigm supported by F#: the manipulation and representation of languages using a variety of concrete and abstract representations. In this chapter, you learn three advanced features of F# programming: F# computation expressions (also called workflows), F# reflection, and F# quotations. These are also used in other chapters, particularly Chapters 13 and 15. Chapter 18, “Libraries and Interoperating with Other Languages,” shows how to use F# with other software libraries. In particular, you learn you how use F# with .NET libraries and look at some of the libraries available. You also learn how to interoperate C# code with COM, learn more about the .NET Common Language Runtime, look at how memory management works, and learn how to use the .NET Platform Invoke mechanisms from F#. Chapter 19, “Packaging, Debugging and Testing F# Code,” shows the primary tools and techniques you can use to eliminate bugs from your F# programs. You learn how to package your code into .NET assemblies, learn about other package sharing techniques, learn how to use the .NET and Visual Studio debugging tools with F#, how to use F# Interactive for exploratory development and testing, and how to use the NUnit testing framework with F# code. Chapter 20, “Designing F# Libraries,” gives our advice on methodology and design issues for writing libraries in F#. You learn how to write vanilla .NET libraries that make relatively little use of F# constructs at their boundaries in order to appear as natural as possible to other .NET programmers. We then cover functional programming design methodology and how to combine it with the OO design techniques specified by the standard .NET Framework design guidelines. The appendix, “F# Brief Language Guide,” gives a compact guide to all key F# language constructs and the key operators used in F# programming. Because of space limitations, we only partially address some important aspects of programming with F#. There are also hundreds of open-source projects related to .NET programming, many with a specific focus on F#. F# can also be used with alternative implementations of the CLI such as Mono, topics we address only tangentially in this book. Quotation meta-programming is described only briefly in Chapter 16, and some topics in functional programming such as the design and implementation of applicative data structures aren’t covered at all. We do not describe how to create new instances of the F# 3.0 feature called “type providers” because excellent material on authoring type providers is available from Microsoft. Also, some software engineering issues such as performance tuning are largely omitted. Who This Book Is For We assume you have some programming knowledge and experience. If you don’t have experience with F#, you’ll still be familiar with many of the ideas it uses. However, you may also encounter some new and challenging ideas. For example, if you’ve been taught that OO design and programming are the only ways to think about software, then programming in F# may be a re-education. F# fully supports OO development, but F# programming combines elements of both functional and OO design. OO patterns such as implementation inheritance play a less prominent role than you may have previously experienced. Chapter 6 covers many of these topics in depth. The following notes will help you set a path through this book, depending on your background: www.it-ebooks.info chapter 1 n IntroductIon 6 C++, C#, Java, and Visual Basic: If you’ve programmed in a typed OO language, you may find that functional programming, type inference, and F# type parameters take a while to get used to. However, you’ll soon see how to use these to be a more productive programmer. Be sure to read Chapters 2, 3, 5, and 6 carefully. Python, Scheme, Ruby, and dynamically typed languages: F# is statically typed and type-safe. As a result, F# development environments can discover many errors while you program, and the F# compiler can more aggressively optimize your code. If you’ve primarily programmed in an untyped language such as Python, Scheme, or Ruby, you may think that static types are inflexible and wordy. However, F# static types are relatively nonintrusive, and you’ll find the language strikes a balance between expressivity and type safety. You’ll also see how type inference lets you recover succinctness despite working in a statically typed language. Be sure to read Chapters 2 to 6 carefully, paying particular attention to the ways in which types are used and defined. Typed functional languages: If you’re familiar with Haskell, OCaml, or Standard ML, you’ll find the core of F# readily familiar, with some syntactic differences. However, F# embraces .NET, including the .NET object model, and it may take you awhile to learn how to use objects effectively and how to use the .NET libraries themselves. This is best done by learning how F# approaches OO programming in Chapters 6 to 8, and then exploring the applied .NET programming material in Chapters 11 to 20, referring to earlier chapters as necessary. Haskell programmers also need to learn the F# approach to imperative programming, described in Chapter 4, because many .NET libraries require a degree of imperative coding to create, configure, connect, and dispose of objects. We strongly encourage you to use this book in conjunction with a development environment that supports F# directly, such as Visual Studio 2012 or Mono Develop 3.0. In particular, the interactive type inference in these environments is exceptionally helpful for understanding F# code; with a simple mouse movement, you can examine the inferred types of the sample programs. These types play a key role in understanding the behavior of the code. n Note You can download and install F# from www.fsharp.net. You can download all the code samples used in this book from www.expert-fsharp.com; they were prepared and checked with F# 3.0. As with all books, it’s inevitable that minor errors may exist in the text. An active errata and list of updates will be published at www. expert-fsharp.com. www.it-ebooks.info 7 n n n chapter 2 Your First F# Program – Getting Started With F# This chapter covers simple interactive programming with F# and .NET. To begin, download and install a version of the F# distribution from www.fsharp.net. (You may have a version on your machine already—for instance, if you have installed Visual Studio.) The sections that follow use F# Interactive, a tool you can use to execute fragments of F# code interactively, and one that is convenient for exploring the language. Along the way, you will see examples of the most important F# language constructs and many important libraries. Creating Your First F# Program Listing 2-1 shows your first complete F# program. You may not follow it all at first glance, but we explain it piece by piece after the listing. Listing 2-1. Analyzing a String for Duplicate Words /// Split a string into words at spaces let splitAtSpaces (text: string) = text.Split ' ' |> Array.toList /// Analyze a string for duplicate words let wordCount text = let words = splitAtSpaces text let wordSet = Set.ofList words let numWords = words.Length let numDups = words.Length - wordSet.Count (numWords, numDups) /// Analyze a string for duplicate words and display the results. let showWordCount text = let numWords, numDups = wordCount text printfn " > %d words in the text" numWords printfn " > %d duplicate words" numDups www.it-ebooks.info [...]... library functions that return Boolean values: let round2 (x, y) = if x >= 100 || y >= 100 then 100 , 100 elif x < 0 || y < 0 then 0, 0 else x, y The operators && and || have the usual short-circuit behavior in that the second argument of && is evaluated only if the first evaluates to true and, likewise, the second argument of || is evaluated only if the first evaluates to false Defining Recursive Functions... www.it-ebooks.info chapter 2 ■ Your First F# Program – Getting Started With F# > let a, b = (1, 2, 3) ;; error FS 000 1: Type mismatch Expecting a 'a * 'b but given a 'a * 'b * 'c The tuples have differing lengths of 2 and 3 Tuples are often used to return multiple values from functions, as in the wordCount example earlier They’re also often used for multiple arguments to functions, and frequently the... the name form Binding this value to a new name doesn’t create a new form; rather, two different handles now refer to the same object (they’re said to alias the same object) For example, the following code sets the title of the same form, despite its being accessed via a different name: let form2 = form form2.Text = 100 then 100 elif x < 0 then 0 else x Conditionals are really shorthand for pattern matching; for example, the previous code could be written like this: let round x = match x with | _ when x >= 100 -> 100 | _ when x < 0 -> 0 | _... let badDefinition1 = let words = splitAtSpaces text let text = "We three kings" words.Length gives error FS0 03 9 : The value or constructor 'text' is not defined 12 www.it-ebooks.info chapter 2 ■ Your First F# Program – Getting Started With F# and let badDefinition2 = badDefinition2 + 1 gives let badDefinition2 = badDefinition2 + 1 error FS0 03 9 : The value or constructor 'badDefinition2' is not defined Within... printfn will look familiar as a variant of printf— printfn also adds a newline character at the end of printing Here, the pattern %d is a placeholder for an integer, and the rest of the text is output verbatim to the console F# also supports related functions, such as printf, sprintf, and fprintf, which are discussed further in Chapter 4 Unlike C/C++, printf is a type-safe text formatter in which the F# ... Started With F# open System.Windows.Forms let form = new Form() form.Visible . stabilized, supported version of F# was F# 2 .0, included with Visual Studio 201 0. In 201 2, Microsoft released F# 3. 0. This is the version of the language described. words.Length gives error FS0 03 9 : The value or constructor 'text' is not defined www.it-ebooks.info 13 chapter 2 n Your FIrst F# program – gettIng started WIth F# and let

Ngày đăng: 21/02/2014, 15:21