Basic F# syntax, types, and functions // Define module MyCode in namespace Company.Rules (lesson 12) module Company.Rules.MyCode // Open System namespace open System // Define a simple value (lesson 4) let playerName = "Joe" // Create and unwrap a tuple (lesson 9) let playerTuple = playerName, 21 let name, age = playerTuple // Define and create a record (lesson 10) type Player = { Name : string; Score : int; Country : string } let player = { Name = playerName; Score = 0; Country = "GB" } // Function definition with copy-and-update record syntax (lessons 10, 11) let increaseScoreBy score p = { p with Score = p.Score + score } // Piping functions (lesson 11) player |> increaseScoreBy 50 |> printfn "%A" // Function with basic pattern matching and nested expressions (lesson 7, 20) type GreetingStyle = Friendly | Normal let greet style player = let greeting = match style with | Friendly -> "Have a nice day!" | Normal -> "Good luck." sprintf "Hello, player %s! %s" player.Name greeting // Partial function application (lesson 11) let friendlyGreeting = greet Friendly // Composing functions together (lesson 11) let printToConsole text = printfn "%s" text let greetAndPrint = friendlyGreeting >> printToConsole Get Programming with F# A guide for .NET developers Isaac Abraham MANNING Shelter Island For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2018 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Acquisitions editor: Michael Stephens 20 Baldwin Road Development editor: Elesha Hyde PO Box 761 Review editor: Aleksandar Dragosavljevic´ Shelter Island, NY 11964 Technical development editor: Mark Elston Technical proofreader: Dane Balia Production editor: David Novak Copyeditor: Sharon Wilkey Proofreader: Melody Dolab Typesetter: Dottie Marsico Cover designer: Monica Kamsvaag ISBN 9781617293993 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 23 22 21 20 19 18 Contents Foreword v Preface viii Acknowledgments x About this book xi About the author xiv Welcome to Get Programming Lesson 13 Achieving code reuse in F# 149 with F#! 1 Lesson 14 Capstone 2 160 Unit 1 Unit 4 F# AND VISUAL STUDIO COLLECTIONS IN F# Lesson 1 The Visual Studio experience 17 Lesson 15 Working with collections in F# 173 Lesson 2 Creating your first F# program 25 Lesson 16 Useful collection functions 186 Lesson 3 The REPL—changing how we develop 34 Lesson 17 Maps, dictionaries, and sets 197 Lesson 18 Folding your way to success 206 Unit 2 Lesson 19 Capstone 3 219 Unit 5 HELLO F# Lesson 4 Saying a little, doing a lot 47 THE PIT OF SUCCESS WITH THE F# TYPE Lesson 5 Trusting the compiler 58 SYSTEM Lesson 6 Working with immutable data 70 Lesson 20 Program flow in F# 231 Lesson 7 Expressions and statements 81 Lesson 21 Modeling relationships in F# 244 Lesson 8 Capstone 1 92 Lesson 22 Fixing the billion-dollar mistake 257 Unit 3 Lesson 23 Business rules as code 270 Lesson 24 Capstone 4 284 TYPES AND FUNCTIONS Unit 6 Lesson 9 Shaping data with tuples 101 Lesson 10 Shaping data with records 111 LIVING ON THE .NET PLATFORM Lesson 11 Building composable functions 125 Lesson 25 Consuming C# from F# 299 Lesson 12 Organizing code without classes 138 Lesson 26 Working with NuGet packages 310 iii iv Contents Lesson 27 Exposing F# types and functions Lesson 37 Exposing data over HTTP 439 to C# 321 Lesson 38 Consuming HTTP data 453 Lesson 28 Architecting hybrid language Lesson 39 Capstone 7 464 applications 331 Lesson 29 Capstone 5 342 Unit 9 Unit 7 UNIT TESTING Lesson 40 Unit testing in F# 477 WORKING WITH DATA Lesson 41 Property-based testing in F# 489 Lesson 30 Introducing type providers 355 Lesson 42 Web testing 501 Lesson 31 Building schemas from live data 365 Lesson 43 Capstone 8 511 Lesson 32 Working with SQL 376 Lesson 33 Creating type provider-backed Unit 10 APIs 388 Lesson 34 Using type providers in the real WHERE NEXT? world 401 Lesson 35 Capstone 6 411 Appendix A The F# community 521 Appendix B F# in my organization 527 Unit 8 Appendix C Must-visit F# resources 537 Appendix D Must-have F# libraries 543 WEB PROGRAMMING Appendix E Other F# language features 556 Lesson 36 Asynchronous workflows 425 Index 564 Foreword When I first met Isaac Abraham in 2015, I knew immediately that he shared my passion for educating .NET developers in the art of F#. His book, which you hold in your hands, is the text I had wanted when I first kindled my F# romance. Inside, Isaac will lead you on a journey of F# that’s both pragmatic and relevant. If you’re a C# or Visual Basic .NET developer, you’ll learn through a series of lessons how to apply F# to everyday .NET development. You won’t have to wade through the deep theoretical explanations that are often the staple of functional programming books. Instead, Isaac will guide you with practical advice and best practices derived from his own experience as an F# developer. I first fell in love with F# when it was still a research language being developed out of Microsoft Research in Cambridge, England. The language was a bit rough around the edges, but every monthly release brought a fresh set of exciting new features to explore. The community was small but already vibrant, eager to evangelize any who would listen about how F# was so expressive, powerful, and fun. I found myself caught up in it all. Since F# was still very new, there weren’t many books available to help me learn the lan- guage. Being a self-taught C# programmer, I wanted something that was light on theory and heavy on practice, but such books hadn’t been written yet. I even made my own meager attempt to fill that void, by writing a blog series (viewable today only via the Internet Archive) titled, “Why I Love F#.” In each blog article, I attempted to present F# to everyday C# developers like myself, highlighting features that marry well with .NET development such as the F# Interactive environment, type-safe format strings, tuples, and pattern matching. I wanted to encourage others to explore this beautiful language that I’d become quite smitten with, and to teach them how to use it effectively to create .NET programs. Eventually, my blog fell by the wayside. After joining the .NET languages team at Microsoft, I could no lon- ger find the time to keep it current and gave it up. Fast-forward to today. Today, F# is more popular than ever and growing at a rapid pace. F# code is running quite literally everywhere: on desktops, mobile devices, the web, IoT v vi Foreword devices, and in the cloud. F# has reached its fourth major version, boasts an active and fiercely passionate community, and enjoys first-class tooling support in many IDEs and editors, such as Visual Studio, Visual Studio for Mac, and JetBrains Rider. And of course, F# books are available on a wide variety of topics, from the more general pur- pose to fully scientific. F# exemplifies an aspect of programming that all too often is forgotten: programming should be fun. With Isaac as your teacher, I’m confident you’ll have an absolute blast. —DUSTIN CAMPBELL PRINCIPAL SOFTWARE ENGINEER, .NET LANGUAGES TEAM, MICROSOFT In the Introduction to F#, Isaac mentions that F# leads you to a pit of success, which is something that I wholeheartedly agree with. I believe that the way this happens has a lot to do with how a pragmatic way of thinking, functional ideas, and a powerful run- time come together in F#. The functional ideas serve as a fantastic tool for understand- ing and modeling the problem domain in a simple way. At the same time, F# gives you a versatile toolbox for solving concrete problems within the domain. This includes a lan- guage that supports multiple paradigms including functional, object-oriented, and imperative, but also powerful .NET and F# libraries. Again, this book introduces F# from exactly the right perspective. It rightly puts a strong emphasis on thinking about the domain in a functional way, but at the same time, it introduces all of the important tools from the F# toolbox. When I started learning the F# language 10 years ago, the typical advice was that F# is just a functional programming language for .NET, so you should “forget everything you know about programming,” read a couple of academic functional programming text- books, and then figure out how to use the functional concepts to write .NET applica- tions on your own. I’m happy that this isn’t the advice we give to people who are curious about F# these days. There are two main reasons for this. First, it turns out that “forgetting everything” is just a poor strategy for learning F# if you have existing programming knowledge. Sec- ond, it also turns out that the “functional programming” label is only partly appropriate for the kind of code you write when using F# to solve real-world problems. This book reflects both points, which is what makes it a fantastic material for learning F#. The difference between F# and other .NET languages is equally easy to overstate and to understate. On one hand, many functional language constructs now exist in C# and VB Foreword vii .NET, so you might think that the difference isn’t that big. On the other hand, F# is rooted in functional programming and leads you to different way of thinking about problems, so you might think that you need to start from a clean slate. As is often the case, the truth is somewhere in the middle. When using F#, you’ll find yourself design- ing software differently and, as a result, falling into the pit of success described in unit 5. At the same time, learning F# shouldn’t be as daunting as it was 10 years ago. You’ll find many similarities to what you know already, and this book does a great job of using them to explain F# clearly and effectively. If you’re a C# or VB .NET developer who cares about solving problems in a pragmatic way, this is the book for you. There’s no need to wait for the “right problem” that will be “well suited to functional programming” and give you an excuse to learn F#. As this book clearly explains, the point of F# isn’t just in functional programming, but in the pit of success, where the F# way of solving problems leads you. —TOMAS PETRICEK PARTNER, FSHARPWORKS Preface Several years ago, when I was a full-time C# developer working for a .NET consultancy in the United Kingdom, I embarked on a goal to improve the quality of software I developed. I was fed up with writing software and having the customer find bugs that I felt I should have caught, and disappointed that I didn’t know how to use OO pro- gramming to model real-world problems. So I learned about SOLID, became a TDD fanatic, and read up on things like dependency injection and design patterns. And my software did improve! My clients were happier, and my managers were pleased with the lower bug rates. But soon afterward, I once again became frustrated with a lack of progress. Did we really need this amount of rigor, of process, and of unit tests in order to become proficient soft- ware developers? I knew that I’d taken a step forward in terms of quality by adopting SOLID and TDD, but I wanted to achieve it in a more productive fashion. I wanted more support from my programming language to do the right thing by default; something that guided me to the “pit of success” without my needing to use a myriad of design patterns in a specific way, and allowed me to get to the heart of a problem that I was try- ing to solve. Fast-forwarding a little, I ended up working for a financial services company working on a rules engine to monitor dodgy-looking trades—things like insider trading. We spent a great deal of time looking at how to create a component-based rules engine with pluggable “rules” that we could use to build “larger” rules. What I discovered by the end was that we had spent the last 18 months trying to implement a functional pipeline using object-oriented constructs and design patterns. So, having heard about F#, I thought I’d give it a look. I was initially interested in it as a means to an end; I’d heard that it could help me write software on .NET more quickly and with fewer bugs. I attended an intensive two-day course, and tried to use F# as much in my own time as I could. Interestingly, while learning F#, I found that it reinvig- orated me as a developer—not only was I learning something entirely new, but I could viii
Description: