Robert Pickering and

Kit Eason

Beginning F# 4.0

2nd ed. 2016

Robert Pickering

St. Germain-En-Laye, France

Kit Eason

Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ .

ISBN 978-1-4842-1375-9

e-ISBN 978-1-4842-1374-2

DOI 10.1007/978-1-4842-1374-2

© Robert Pickering and Kit Eason 2016

Beginning F# 4.0

Managing Director: Welmoed Spahr

Lead Editor: James DeWolf

Development Editor: Douglas Pundick

Technical Reviewer: Fabio Claudio Ferracchiati

Editorial Board: Steve Anglin, Pramila Balen, Louise Corrigan, James DeWolf, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing

Coordinating Editor: Melissa Maldonado

Copy Editor: Mary Behr

Compositor: SPi Global

Indexer: SPi Global

Artist: SPi Global

For information on translations, please e-mail [email protected] , or visit www.apress.com .

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales .

Standard Apress

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

For Noah and Darwin.

Foreword

That moment. That secret weapon moment. That I-got-lucky-and-came-across-something-that-helped-me-win-the-game moment. This might just be it.

This book teaches you all you need to know to get going with F#, an open source, cross-platform programming language suitable for just about every kind of programming and data processing task. And yes, learning F# is like learning a secret weapon. Wielding it, you will find yourself doing things previously beyond your limits: it will empower you, and with it you will do great things.

Why do I know this? Because I have seen the authors of this book, Kit Eason and Robert Pickering, learn F# and wield it powerfully and effectively in job after job. I’ve seen how it has changed the way they think about programming. In this book, they share what they have learned with you, and they want to help you learn and use this secret weapon too.

No programming language is a “silver bullet;” F# won’t magically slay dragons in and of itself. However, F# does an excellent job of removing the incidental complexity that bedevils so much of programming. Take one example: the pervasive use of “null” values in languages such as C# and Java. In one real-world case study by Simon Cousins, using F# reduced the incidence of null checks by 200x in a transaction processing engine, with over 3,000 extra null checks in the fully object-oriented application in question. This is no minor thing: to continue the secret weapon analogy, a null check is like a potential weapon failure at a critical moment, a gun-jam. At any one of these 3,000 code points, that application was at risk of failing. It is simply better–and less risky–to fight your battles with a weapon that doesn’t jam. F# reduces the number of potential failure points, and does so systematically. Some argue that incidental complexity is not important. This is wrong: removing incidental complexity is the first and most essential step you can take to becoming a more productive programmer, since it liberates you to address the real heart of programming. Learning F# will help you do this.

F# is known as a “functional-first” programming language, meaning you use simple functional programming as the first way to solve most problems. This is simple and easy, and lets you solve most programming problems with ease. F# programming is, however, pragmatic. Good software engineering really matters in F#: we care about code quality, naming, documentation, and good design. This book will show you all of these things. It will also teach you how to use F# for data access, web programming, parallel programming, and a myriad of other practical tasks. Finally, it will show you how to contribute back to the F# community through open source packages.

Take the moment and learn F#, and don’t look back. Thousands of people are enjoying this language daily, and with more efficient, expressive coding, and higher productivity. And not just productivity, but delight and happiness in craftsmanship as well.

Don Syme

Acknowledgments

The first vote of thanks must go to the person who changed my professional life, and those of many others: Don Syme, the “father of F#.” Don does invaluable work in mentoring and encouraging me and the whole F# community. He sets a positive tone that is reflected in everything the community does.

Huge thanks also to Fabio Claudio Ferracchiati, our technical reviewer, who has turned around reams of material in what seems like record time.

Thanks also to the various employers who have supported me (admittedly with varying degrees of scepticism!) during my journey into F#. Extra special thanks to Edoardo Turelli and all the team at Adbrain, who have somehow unlocked the secret of having the right people working on the right problems in the right way.

I’m deeply indebted to the many members of the F# community (both open source and within Microsoft) who have grown F# from an academic project to a thriving commercial and scientific language with a broad-based ecosystem. Every commit counts!

I’d like to thank everyone at Apress who contributed to this book, notably James DeWolf, Melissa Maldonado, and Douglas Pundick. Thank you for your patience, professionalism, and support.

Finally, huge appreciation to my wife, Val, for her unstinting support in everything I do; and to my children, Matt and Kate, both of them frankly more talented developers than I, for keeping me on my toes.

Contents

  1. Chapter 1:​ Getting Started
    1. What Is Functional Programming?​
    2. Why Is Functional Programming Important?​
    3. What Is F#?​
    4. Who Is Using F#?​
    5. Who Is This Book For?​
    6. What’s Next?​
  2. Chapter 2:​ How to Obtain, Install, and Use F#
    1. Obtaining F# on Microsoft Windows
    2. Obtaining F# on Apple OS X
    3. Obtaining F# on Linux
    4. The Examples in This Book
    5. Summary
  3. Chapter 3:​ Functional Programming
    1. Literals
    2. Anonymous Functions
    3. Identifiers and let Bindings
      1. Identifier Names
      2. Scope
      3. Capturing Identifiers
      4. The use Binding
    4. Recursion
    5. Operators
    6. Function Application
    7. Partial Application of Functions
    8. Pattern Matching
    9. Control Flow
    10. Lists
      1. Pattern Matching Against Lists
      2. List Comprehensions
    11. Types and Type Inference
    12. Defining Types
      1. Tuple and Record Types
      2. Union or Sum Types (Discriminated Unions)
      3. Type Definitions with Type Parameters
      4. Recursive Type Definitions
    13. Active Patterns
      1. Complete Active Patterns
      2. Partial Active Patterns
    14. Units of Measure
    15. Exceptions and Exception Handling
    16. Lazy Evaluation
    17. Summary
  4. Chapter 4:​ Imperative Programming
    1. The Unit Type
    2. The Mutable Keyword
    3. Defining Mutable Records
    4. The Reference Type
    5. Arrays
    6. Array Comprehensions
    7. Array Slicing
    8. Control Flow
    9. Calling Static Methods and Properties from .​NET Libraries
    10. Using Objects and Instance Members from .​NET Libraries
    11. Using Indexers from .​NET Libraries
    12. Working with Events from .​NET Libraries
    13. Pattern Matching over .​NET Types
    14. The | > Operator
    15. Summary
  5. Chapter 5:​ Object-Oriented Programming
    1. Records As Objects
    2. F# Types with Members
    3. Object Expressions
    4. Defining Classes
    5. Optional Parameters
    6. Additional Constructors
    7. Defining Interfaces
    8. Implementing Interfaces
    9. Classes and Inheritance
    10. Methods and Inheritance
    11. Accessing the Base Class
    12. Properties and Indexers
    13. Autoproperties
    14. Overriding Methods from Non-F# Libraries
    15. Abstract Classes
    16. Classes and Static Methods
    17. Casting
    18. Type Tests
    19. Defining Delegates
    20. Structs
    21. Enums
    22. Summary
  6. Chapter 6:​ Organizing, Annotating, and Quoting Code
    1. Modules
    2. Namespaces
    3. Opening Namespaces and Modules
    4. Giving Modules Aliases
    5. Signature Files
    6. Private and Internal let Bindings and Members
    7. Module Scope
    8. Module Execution
    9. Optional Compilation
    10. Comments
    11. Doc Comments
    12. Comments for Cross-Compilation
    13. Custom Attributes
    14. Quoted Code
    15. Summary
  7. Chapter 7:​ The F# Libraries
    1. The Native F# Library FSharp.​Core.​dll
      1. The FSharp.​Core.​Operators Module
      2. The FSharp.​Reflection Module
      3. The FSharp.​Collections.​Seq Module
      4. The FSharp.​Text.​Printf Module
      5. The FSharp.​Control.​Event Module
    2. Summary
  8. Chapter 8:​ Data Access
    1. The System.​Configuration Namespace
    2. The System.​IO Namespace
    3. Using Sequences with System.​IO
    4. The System.​Xml Namespace
    5. ADO.​NET
    6. Data Binding
    7. Data Binding and the DataGridView Control
    8. Using Dapper to Access Relational Data
    9. ADO.​NET Extensions
    10. Introducing LINQ
    11. Using LINQ to XML
    12. Summary
  9. Chapter 9:​ Parallel Programming
    1. Threads, Memory, Locking, and Blocking
    2. Reactive Programming
    3. Data Parallelism
      1. The Array.​Parallel Module
      2. The FSharp.​Collections.​ParallelSeq Module
    4. Asynchronous Programming
    5. Message Passing
    6. Summary
  10. Chapter 10:​ Distributed Applications
    1. Networking Overview
    2. Using HTTP
    3. Using HTTP with Google Spreadsheets
    4. Using Suave.​io
    5. Creating Web Services
    6. Summary
  11. Chapter 11:​ Language-Oriented Programming
    1. What Is Language-Oriented Programming?​
    2. Data Structures as Little Languages
      1. A Data Structure–Based Language Implementation
    3. Metaprogramming with Quotations
    4. Implementing a Compiler and an Interpreter for an Arithmetic Language
      1. The Abstract Syntax Tree
      2. Interpreting the AST
      3. Compiling the AST
      4. Compilation vs.​ Interpretation
    5. Summary
  12. Chapter 12:​ Compatibility and Advanced Interoperation
    1. Calling F# Libraries from C#
      1. Returning Tuples
      2. Exposing Functions That Take Functions As Parameters
      3. Using Union Types
      4. Using F# Lists
      5. Defining Types in a Namespace
      6. Defining Classes and Interfaces
    2. Calling Using COM Objects
    3. Using COM-Style APIs
    4. Using P/​Invoke
    5. Using F# from Native Code via COM
    6. Summary
  13. Chapter 13:​ Type Providers
    1. What Are Type Providers?​
    2. Using the CSV Type Provider
    3. Using the HTML Type Provider
    4. Answering Some Questions with the HTML Type Provider
      1. Rank the Stations by Traffic
      2. Finding All of the Stations on the Northern Line
      3. Which Station Has the Most Distinct Letters in Its Name?​
    5. Using the SQL Client Type Provider
    6. Joining Datasets from Differing Data Sources
    7. Summary
  14. Index

About the Authors and About the Technical Reviewer

About the Authors

Robert Pickering is a Microsoft MVP acknowledged as a community leader and a world class expert on F#. In his ten year career as a software engineer he has participated in a wide range of projects building large, scalable, and fault tolerant systems on the Microsoft .NET platform. He has experience in both consulting and working as an engineer for a software house. He has been invited to speak at prestigious events such as Microsoft TechEd, JAOO, and TechDays Paris. He has been involved in organizing conferences as track lead for events such as Functional Programming eXchange, London, and he organizes the ALT.NET community meetings in Paris. He has also appeared in podcast and screen casts such as dnrtv.com and hanselminutes.com.

Kit Eason is a software developer and educator with 30 years of experience in industries from automotive engineering through university supercomputing to energy trading. He currently works as a senior developer at Adbrain ( www.adbrain.com ), a leading data intelligence company that empowers marketers to regain control of their customer relationships in today’s hyperconnected yet highly fragmented world. Kit also works as an author for Pluralsight: his courses there include “F# Jumpstart” and “F# Functional Data Structures.” He has also appeared on the “.NET Rocks!” podcast.

About the Technical Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works for Blu Arancio ( www.bluarancio.com ). He is a Microsoft Certified Solution Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional, and a prolific author and technical reviewer. Over the past ten years, he’s written articles for Italian and international magazines and coauthored more than ten books on a variety of computer topics.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.46