Mastering F#
5/5
()
About this ebook
Related to Mastering F#
Related ebooks
F# High Performance Rating: 0 out of 5 stars0 ratingsScala Functional Programming Patterns Rating: 0 out of 5 stars0 ratingsClojure Reactive Programming Rating: 0 out of 5 stars0 ratingsClojure for Java Developers Rating: 0 out of 5 stars0 ratingsF# for Machine Learning Essentials Rating: 0 out of 5 stars0 ratingsFunctional Programming in C#, Second Edition Rating: 0 out of 5 stars0 ratingsLearning Elixir Rating: 0 out of 5 stars0 ratingsLearning F# Functional Data Structures and Algorithms Rating: 0 out of 5 stars0 ratingsMastering Clojure Rating: 0 out of 5 stars0 ratingsBackbone.js Patterns and Best Practices Rating: 0 out of 5 stars0 ratingsIntroduction to JVM Languages Rating: 0 out of 5 stars0 ratingsInteractive Applications Using Matplotlib Rating: 0 out of 5 stars0 ratingsLearning Reactive Programming with Java 8 Rating: 0 out of 5 stars0 ratingsLearning .NET High-performance Programming Rating: 0 out of 5 stars0 ratingsJava 9 with JShell Rating: 0 out of 5 stars0 ratingsData-oriented Development with AngularJS Rating: 0 out of 5 stars0 ratingsGetting Started with Julia Rating: 0 out of 5 stars0 ratingsKivy: Interactive Applications in Python Rating: 0 out of 5 stars0 ratingsF# 4.0 Design Patterns Rating: 0 out of 5 stars0 ratingsMastering Apache Camel Rating: 0 out of 5 stars0 ratingsClojure Programming Cookbook Rating: 0 out of 5 stars0 ratingsThe Clojure Workshop: Use functional programming to build data-centric applications with Clojure and ClojureScript Rating: 0 out of 5 stars0 ratingsReal-World Functional Programming: With examples in F# and C# Rating: 0 out of 5 stars0 ratingsFunctional Programming in Scala Rating: 4 out of 5 stars4/5Clojure Web Development Essentials Rating: 0 out of 5 stars0 ratingsGet Programming with Haskell Rating: 0 out of 5 stars0 ratingsBuilding Python Real-Time Applications with Storm Rating: 0 out of 5 stars0 ratingsGet Programming with F#: A guide for .NET developers Rating: 0 out of 5 stars0 ratingsGet Programming with Scala Rating: 0 out of 5 stars0 ratingsGetting Started with LLVM Core Libraries Rating: 0 out of 5 stars0 ratings
Internet & Web For You
How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Get Rich or Lie Trying: Ambition and Deceit in the New Influencer Economy Rating: 0 out of 5 stars0 ratingsNo Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5Coding For Dummies Rating: 5 out of 5 stars5/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsSix Figure Blogging Blueprint Rating: 5 out of 5 stars5/5More Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Podcasting For Dummies Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5The Logo Brainstorm Book: A Comprehensive Guide for Exploring Design Directions Rating: 4 out of 5 stars4/5How To Start A Podcast Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5Remote/WebCam Notarization : Basic Understanding Rating: 3 out of 5 stars3/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5Cybersecurity For Dummies Rating: 4 out of 5 stars4/5Stop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5The Internet Is Not What You Think It Is: A History, a Philosophy, a Warning Rating: 4 out of 5 stars4/5Wireless Hacking 101 Rating: 4 out of 5 stars4/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5
Reviews for Mastering F#
1 rating1 review
- Rating: 5 out of 5 stars5/5la pregunta es! están traducidos al español estos libros? espero su pronta respuesta Gracias?
Book preview
Mastering F# - Alfonso García-Caro Núñez
Table of Contents
Mastering F#
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started in F#
Key features of F#
Functional and imperative languages
F# and integrated development environments
Using F# with Visual Studio
F# project structure
F# Script File
Using the F# Interactive window
The Visual Studio interactive window
The FSI interactive window
Basic values
Getting started with functions
Partially applied functions
Recursive functions
Higher-order functions
Summary
2. Functional Core with F#
F# primitive types
The unit type
Operator precedence
Custom operators
Immutability, type declarations, and strong type inference
Pattern matching
Functions with pattern matching
Pattern expressions
Guard expressions
Incomplete matches
Wildcard pattern
Tuples
Value matching
Records
Updating records
Functional update
Mutable fields
Field label declarations
Value matching
Common Language Infrastructure mutable records
Union cases
Options in F#
Structural equality and comparison
Custom equality and comparison
Reference cells and side-effects
Active patterns
Partial active patterns
Summary
3. Data Structures in F#
F# Collections
Sequence
Sequence expressions
Working with Seq functions
Creating sequences
Searching and finding elements
Sequence generators
Sequence computation operations
Arrays
Working with Array functions
Arrays and tuples
Array comprehensions
Array.Parallel module
Lists
Tail recursion
List and tuples
List comprehensions
Sets
Map
Advanced data structures
Binary trees
Balanced red-black trees
Summary
4. Imperative Programming in F#
Control structures
Looping
The for...to expression
The for...in expression
The while...do expression
Conditions
Working with conditions
Object-oriented programming
Defining a class
Constructors
Structs
Declaring fields, properties, methods, and static methods
Fields
Explicit fields
Properties
Static properties
Indexed properties
Methods
Static methods
Abstract and virtual methods
Parameters
Inheritance
Abstract
Defining an interface
Implement interface in F# types
Interface inheritance
Extensions
Generics
Using generic constructs
Wildcard generic constructs
Generic constraints
Generic extensions
Using LINQ in F#
Events
Declaring events
Event processing
Declaring delegates
Observables
Interop with C#
Optional parameters
Algebraic data types
Generic extensions consumable in C#
Exposing F# functionality to C#
Summary
5. Asynchronous Programming
Asynchronous workflows in F#
Using let!
Understanding async workflows
Async module
Async.AsBeginEnd
Async.AwaitEvent
Async.AwaitIAsyncResult
Async.AwaitWaitHandle
Async.AwaitTask
Async.FromBeginEnd
Async.FromContinuations
Async.Start
Async.StartChild
Async.StartAsTask
Async.StartChildAsTask
Async.StartImmediate
Async.SwitchToNewThread
Async.SwitchToThreadPool
Async.SwitchToContext
Async.Parallel
Async.OnCancel
Actor programming with MailboxProcessor
Design patterns with MailboxProcessor
Type-safe MailboxProcessor, an imperative approach
Type-safe MailboxProcessor, a functional approach
Messages and union types
Reporting results from the mailbox
Agents and errors
MailboxProcessor functions
Implementing a non-blocking queue
Reactive programming with async workflows
Summary
6. Type Providers
SQL type provider
Preparing the test database
Using the type provider
Querying the data
SQL entity type provider
Using the type provider
Querying the data
OData type provider
Prerequisites
Using the type provider
Querying the data
Web service type provider
Prerequisites
Using the type provider
Querying the data
Data analysis with type providers
Prerequisites
Using the type provider
Query builder
Summary
7. Web Programming in F#
ASP.NET Web API 2
Suave
Routing with Suave
Templating with Suave
WebSharper
Installing WebSharper
Sitelets
UI.Next
Fable
Using Fable with React
Summary
8. Application Development in F#
GitHub Electron
npm
webpack
Using React components with Electron
npm start
Automatic refresh on code changes
Using Node APIs from the renderer process
Summary
9. Testing in F#
Unit testing
Unit tests with NUnit
Setting up the test environment
Mocking
F# idiomatic assertions
Asynchronous tests
Running NUnit tests with FAKE
NUnit and Fable
Property-based testing
Integrating FsCheck and NUnit
Automated browser testing
Summary
10. Distributed Programming in F#
Actor Model
MailboxProcessor
Akka.NET
Supervision
Remote actors
Summary
Mastering F#
Mastering F#
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2016
Production reference: 1251116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78439-343-4
www.packtpub.com
Credits
About the Authors
Alfonso García-Caro Núñez is a linguist who, in recent years, changed the study of natural languages by the practice of their programming counterparts. He currently focuses on JavaScript and .NET development and has worked on developing mobile, web, and desktop applications for several industries, such as video games, education, green energy, or digital performances. He is also an international speaker who has presented at several conferences around the globe. His admiration for both the thriving JavaScript ecosystem and functional programming with F# made him look for a way to bring together both worlds, leading to the creation of Fable, an F# to JavaScript compiler that is attracting lot of attention from the community, and integrates the power and elegance of F# with the hundreds of JavaScript tools and libraries available.
I would like to say a big thank you to all the members of the incredibly supportive and welcoming F# community. Since my first timid steps into functional programming, I have been always encouraged to give my opinion and contribute to the development of the ecosystem and the language itself. Features and tools are important, but it is openness and collaboration that really makes you proud to belong to a community. Neither this book nor anything else in my life would have been possible without the care and love of my family. I dedicate this as well as all my work to the women of my life: my mother, wife, and daughter.
Suhaib Fahad is an entrepreneur and is running a startup; he is also an expert F# programmer and enthusiast, using F# in various domains within the products that he is building. He is extremely passionate about developing in functional languages and loves to engage with developers of different communities. He has also been researching and working with cloud scale applications since 2012. Fahad lives in Bangalore, the IT hub of India, with his wife and baby boy.
About the Reviewer
Dr Basel Abu-Jamous is a post-doctorate researcher in the area of bioinformatics at the University of Oxford. He is interested in the development of new computational algorithms that address bioinformatic questions with a special focus on tunable consensus clustering methods. He is also interested in the application of such methods in biology and medicine. For instance, he currently works in Dr. Steven Kelly’s laboratory within the C4 Rice Project that aims to improve photosynthetic efficiency in rice and thus to enhance crop yields. As such, the C4 Rice Project is one of the scientific Grand Challenges of the 21st century, involving the coordinated efforts of researchers from 12 institutions in eight countries.
Previously, while being in the group of Professor Asoke Nandi at Brunel University London, he worked closely with Professor David Roberts, the Professor of Hematology at John Radcliffe Hospital and the University of Oxford, to understand the genetic programs responsible for erythropoiesis, that is, the production of red blood cells in human bodies. He was also in collaboration with Professor Adrian Harris and Professor Francesca Buffa, experts in breast cancer at Churchill Hospital and the University of Oxford, to analyze genetic regulatory pathways in breast cancer tumors under hypoxia, that is, low levels of oxygen. Additionally, he was also involved in the analysis of data from other areas including baker’s yeast, malaria, and E. coli bacteria.
Dr Abu-Jamous received his Ph.D. from Brunel University London in July 2015 and was awarded the Dean’s Prize for Innovation and Impact in Doctoral Research in the area of electronic and computer engineering in December of the same year. In January 2015, he was appointed by Professor Nandi as a research assistant at Brunel University London, and in July 2016 he moved to the University of Oxford.
He has published eight journal papers, fourteen peer-reviewed full-length papers in international conferences, and a research monograph book (Abu-Jamous, Fa, and Nandi, Integrative cluster analysis in bioinformatics, John Wiley & Sons, 2015).
Dr Abu-Jamous would like to thank the C4 Rice Project for funding his current research, Brunel University London and the UK National Institute for Health Research (NIHR) for funding his Ph.D. degree and his previous post-doctorate research (NIHR grant reference number RP-PG-0310-1004). He would also like to thank his current and previous supervisors, Dr Steven Kelly and Professor Nandi, respectively, and all colleagues, collaborators, friends, and family for their support.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
F# is a multiparadigm programming language that encompasses object-oriented, imperative, and functional programming language properties. Now adopted in a wide range of application areas and supported both by industry-leading companies who provide professional tools and by an active open community, F# is rapidly gaining popularity as it emerges in digital music advertising and creating music focused ads for Spotify, Pandora, Shazam, and anywhere on the web.
What this book covers
Chapter 1, Getting Started with F#, explains how to get started with F# with Visual Studio. A Simple hello world program is created and details about the project structure and file ordering and the differences between F# and C# in terms of usage are discussed.
Chapter 2, Functional Core with F#, teaches you about the functional core of F#, such as data types, type declarations, immutability, strong type interference, pattern matching, records, F# data structures, sequence expressions, lazy evaluation, making side effects explicit, and so on.
Chapter 3, Data Structures in F#, helps you understand how to use the available data structures in F# and write some basic custom data structures.
Chapter 4, Imperative Programming in F#, teaches you how to use control structures, more idiomatic .NET with F#, and interfacing with C# and generics.
Chapter 5, Asynchronous Programming, goes through the asynchronous programming model in F#, with a bit of cross-referencing or comparison drawn with the C# world.
Chapter 6, Type Providers, talks about some of the most common type providers, and additionally, also looks at the Query build that will help write LINQ-like queries for our custom collections.
Chapter 7, Web Programming in F#, teaches you how to build web servers using some of the most common .NET libraries as well as how you can write code for the browser in F# using WebSharper or Fable.
Chapter 8, Application Development in F#, explains how to write cross-platform desktop applications in F# using Fable and the Github Electron project.
Chapter 9, Testing in F#, teaches you how to write unit tests in F# with popular tools, and the advantages the language offers for this.
Chapter 10, Distributed Programming in F#, delves into using F# to implement the actor model popularized by Erlang, in order to write more robust software using decoupled actors that can run on different machines over a network and heal themselves in the eventuality of failure.
What you need for this book
All you need for this book is a computer that can comfortably run the following software applications: An F# IDE like Visual Studio 2015 (with Visual F# Power Tools), Visual Studio for Mac or Visual Studio Code with the Ionide extension.
Who this book is for
If you are a C# developer with a basic knowledge of F# and want to explore the functional programming paradigm further to master your F# skills, then this book is for you.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The class overrides a ToString function from the base class.
A block of code is set as follows:
let x = 20
if not (x < 10) then
printfn x is greater than 10
Any command-line input or output is written as follows:
> let p = new Point(10, 20);;
val p : Point = Point 10, 20
New terms and important words are shown in bold.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-FSharp. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
Chapter 1. Getting Started in F#
F# is a functional first language in the .NET family and is a derivative of the Meta-Language (ML) family of languages. It shares many features with dialects of ML, which originally derives from the classical ML language designed by Robin Milner in 1973 at the University of Edinburgh. As a .NET language, F# code compiles to Microsoft Intermediate Language (MSIL), which runs on top of Common Language Runtime (CLR).
In this chapter, we will cover the following topics:
The key features of F#
The functional and imperative languages
Using F# with Visual Studio
Basic expressions in F#
Key features of F#
The following are some points that Distinguish the F# language from other .NET languages:
F# is a functional first language, which means that functions are treated as first-class citizens, but it also provides ways to work with other paradigms, such as object-oriented programming (OOP) (as in C#).
Unlike other languages, such as C#, which mixes expressions (language constructs returning a value) and statements (constructs that don't return a value), F# is an expression-based language. You can think of every syntax construct in F# as a small function.
F# is a strongly-typed language, meaning that the type of every expression in the program is determined at compile time. This allows the compiler to make verifications in our code and enables great tooling support, such as autocompletion, refactoring, and so on.
Additionally, F# has a very strong type inference mechanism to infer types for the expressions in a program. This removes much of the verbosity usually associated with strongly-typed languages.
The .NET generics' type system is baked into the core of F#. For example, the programmer doesn't have to specify the functions to be generic; if the F# type system infers the variables can be generic (provided it is implemented that way), the function becomes generic. This makes it easier to write polymorphic code, that is, functions that can be reused with different types.
F# has a module system that allows data structures to be specified and defined abstractly. Unlike C# namespaces, F# modules can contain functions that help you separate data (types) from logic (functions in modules).
F# implements a pattern matching mechanism, which allows controlling conditions based upon structural similarities; whereas, other languages only allow value matching as in IF...ELSE statements in C#.
Functional and imperative languages
Imperative languages usually modify the state of a variable for most operations. This makes it more difficult to reason about our program, particularly when different parts of our code change values that are globally accessible. When a piece of code modifies a value outside its scope, we talk about side-effects (this may also include other state modifications, such as file or console operations). OOP tries to tame side-effects by encapsulating state. However, this is not always a complete solution, as objects often develop tight and complex dependencies with each other that are still difficult to reason with.
Functional languages solve this problem using pure functions. Pure functions are closer to the mathematical ideal of functions, in the sense that they don't have side-effects (don't change state outside their scope) and always produce the same output given the same input. Pure functions are easier to refactor and reason with because their output is predictable, and can be used as building blocks to write large programs with different techniques of function composition.
F#, as described, is a functional-first language, but the language can also deal with unavoidable side-effects such as file or logging operations.
To compare F# with a more imperative language, we can take the example of a Fibonacci sequence generator, as follows:
Note
For illustration purposes, C# in procedural style is used. It is also capable of more functional implementations, such as Language Integrated Query (LINQ). Also, performance is not taken into consideration.
In an imperative language, the algorithm is normally implemented as a loop, and progress is made by modifying the state of the variables used