Join the discussion @ p2p.wrox.com Wrox Programmer to Programmer 7 Foreword by Scott Hanselman, Program Manager, Microsoft Ted Neward, Aaron C. Eriekson, Talbott Crowell, Richard Minerich asm. www.it-ebooks.info PROFESSIONAL F# 2.0 FOREWORD xxi INTRODUCTION xxiii • PARTO BEGINNINGS CHAPTER 1 Primer 3 • PARTI BASICS CHAPTER 2 Lexical Structure 31 CHAPTER 3 Primitive Types 37 CHAPTER 4 Control Flow 47 CHAPTER 5 Composite Types 55 CHAPTER 6 Pattern Matching 85 • PART II OBJECTS CHAPTER 7 Complex Composite Types 105 CHAPTER 8 Classes 125 CHAPTER 9 Inheritance 161 CHAPTER 10 Generics 183 CHAPTER 11 Packaging 191 CHAPTER 12 Custom Attributes 197 • PART III FUNCTIONAL PROGRAMMING CHAPTER 13 Functions 209 CHAPTER 14 Immutable Data 225 CHAPTER 15 Data Types 247 CHAPTER 16 List Processing 257 CHAPTER 17 Pipelining and Composition 269 Continues www.it-ebooks.info • PART IV APPLICATIONS CHAPTER 18 C# 283 CHAPTER 19 Databases 297 CHAPTER 20 XML 317 CHAPTER 21 ASP.NET MVC 341 CHAPTER 22 Silverlight 357 CHAPTER 23 Services 377 INDEX 391 www.it-ebooks.info PROFESSIONAL F# 2.0 Ted Neward Aaron C. Erickson Talbott Crowell Richard Minerich WILEY Wiley Publishing, Inc. www.it-ebooks.info Professional F# 2.0 Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2011 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-52801-3 ISBN: 978-1-118-00713-6 (ebk) ISBN: 978-1-118-00827-0 (ebk) ISBN: 978-1-118-00828-7 (ebk) Manufactured in the United States of America 10 987654321 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., Ill River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http : / /www. wiley. com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro- motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the pub- lisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2010932419 Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade- marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. www.it-ebooks.info To Charlotte: thank you. —TED NEWARD For my grandmother who gave me confidence to write, and for my kids for giving me a reason to. —AARON C. ERICKSON This book is dedicated to my family. —TALBOTT CROWELL To Lou Franco, beyond being a mentor and friend, you showed me that tuhat I once thought hard tuas in fact easy. —RICHARD MINERICH www.it-ebooks.info CREDITS ACQUISITIONS EDITOR Paul Reese DEVELOPMENT EDITOR Kelly Talbot TECHNICAL EDITORS Jason Mauer Matthew Podwysockl Al Scherer David Morton PRODUCTION EDITOR Rebecca Anderson COPY EDITOR San Dee Phillips EDITORIAL DIRECTOR Robyn B. Slesky EDITORIAL MANAGER Mary Beth Wakefield PRODUCTION MANAGER Tim Tate VICE PRESIDENT AND EXECUTIVE GROUP PUBLISHER Richard Swadley VICE PRESIDENT AND EXECUTIVE PUBLISHER Barry Pruett ASSOCIATE PUBLISHER Jim Mlnatel PROJECT COORDINATOR, COVER Lynsey Stanford PROOFREADER Shellah Ledwldge, Word One New York INDEXER Johnna VanHoose Dlnse COVER DESIGNER Michael E. Trent COVER PHOTO © hfng/lstockphoto.com www.it-ebooks.info ABOUT THE AUTHORS TED NEWARD is the Principal with Neward & Associates, a consulting firm that works with clients of all sizes, from Fortune 500s to small startups. He is fascinated with programming languages, virtual machines, and enterprise-class systems, spends a lot of his time in the Java and .NET ecosys- tems, and has recently begun to explore the world of mobile devices and games. He resides with his wife, two sons, and eight laptops in the Pacific Northwest. AARON C. ERICKSON is a Principal Consultant with ThoughtWorks. His life's work is helping organizations better leverage technology by contributing to solutions that have substantial positive economic impact for his clients. He is an enthusiast of agile techniques for delivery of software, and he has a special interest in helping companies understand how to leverage functional programming techniques to perform meaningful business analytics, particularly using natural language processing and Monte Carlo simulation. TALBOTT CROWELL is a Solution Architect and founder of ThirdM responsible for designing and building enterprise applications with a focus on Microsoft technologies including SharePoint, BizTalk Server, and the .NET framework. His company delivers solutions and services to large and small companies, including Fortune 500s. ThirdM also assists companies with the develop- ment process by using a blend of Agile and traditional methodologies, Team Foundation Server and Visual Studio Team System, Scrum, Test Driven Development (TDD), performance testing, and other proven tools and practices. Involved in the developer community, Talbott co-founded the F# User Group, http: //fsug.org, and serves as a lead for other community events and groups such as SharePoint Saturday Boston and the Boston Area SharePoint User Group. You can follow him on twitter, @talbott, or http: //twitter, com/talbott. RICHARD MINERICH began to notice a problem in the software industry only a few years after gradu- ating from UMass Amherst. He saw a deep divide between the remarkable advancements being made in computer science and the aged tools still in use by software engineers and domain experts. Through writing, speaking, and consulting, Richard hopes to bring these advances to a broader audience, to facilitate the creation of intelligent software, and to bring disruptive change to stagnant industries. Richard is currently a Microsoft MVP for the F# programming language and is one of three leaders of the New England F# User Group. www.it-ebooks.info ACKNOWLEDGMENTS FIRST AND FOREMOST, I would like to thank Aaron, Rick, and Talbott for swooping in at the last second, carving off chunks of the vastly-overwhelming "TODO" list remaining to me, and knock- ing them off with nary a complaint or challenge. You guys have been a delight to work with. A tip of the hat must also go to Don Syme, Luke Hoban, Chris Smith, and the others on the F# team, who patiently answered stupid question after stupid question. Thanks must also go out to the vari- ous attendees who've listened to me prattle on about F#, both those who knew more about the subject than I, as well as those who knew less — all of you have been extremely helpful in honing the delivery of the answer to the question, "What is F#, why do I care, and how do I use it?" Matt Podwysocki in particular gets a hearty kudo for helping me understand some of the thornier func- tional concepts, and Kevin Hazzard gets one just for being himself. Lastly, no book gets written without a support structure, and in this case, that structure consists principally of my wife, Charlotte, who patiently endured night after night of "I promise I'll be home by midnight" and wound up waiting for me 'til 3 or 4 AM, just to hear how my day (er night) went. Hon, you deserved much better than me, but I'll never tell, on the off chance that you haven't figured it out yet. —TED NEWARD I WOULD LIKE TO thank, my wife, my kids, and my professional colleagues for their support through this process. Of course, a hearty thanks goes to the folks at Wrox who have been very patient along the way, especially during those times where billable consulting time conflicted with book writing time. Of course, without all the great people in the F# community, this book would not have hap- pened. Particular thanks goes to Alex Pedenko, who helped me vet the Relational Record Mapper concept, nicely extending the work I started in the data chapter. —AARON C. ERICKSON www.it-ebooks.info ACKNOWLEDGMENTS I WOULD LIKE TO thank my family, especially my wife Pradeepa and two sons, Tristan and William, for their support and patience while I worked on this book. I would also like to thank my parents and siblings who have also been major supporting factors in my life. I would like to extend my grati- tude toward my co-authors, Ted Neward, Aaron Erickson, and Rick Minerich for their dedication to getting this book published, Michael de la Maza for spearheading the F# User Group, Don Syme and Microsoft Research for their brilliant work creating F#, plus Luke Hoban and the Microsoft product team for bringing F# into Visual Studio as part of the product. —TALBOTT CROWELL NO AMOUNT OF THANKS to my co-authors would be enough. Ted, for bringing vision and leadership to this project. Aaron, for his frequent advice on dealing with the many small dramas of the author- ing and consulting world. Talbott, for recommending me for this project and for being my New England F# brother-in-arms. I'd also like to thank Michael de la Maza who came up with the idea to start a New England F# User Group, everyone at Atalasoft for supporting me in this and my par- ents for cheering me up when the pressures seemed worst. Finally, I'd like to thank the F# commu- nity; each of you proves the superiority of statically-typed functional programming on a daily basis. —RICHARD MINERICH www.it-ebooks.info [...]... m a r y 289 Calling F# Libraries from C# 289 Basics of Calling F# 290 F# Tuples in C # Programs 290 Dealing w i t h F# Records f r o m C # 291 Passing Functions to F# Functions 292 Dealing w i t h F# Discriminated Unions from C# 292 W o r k i n g w i t h F# O p t i o n Types f r o m C # Rules of Thumb for Writing F# APIs Summary www.it-ebooks.info 293 294 295 CONTENTS CHAPTER 19: DATABASES 297 Overview... of this writing, unfortunately, no "Visual 2 0 1 0 F# Express" edition download exists from Microsoft, so you'll need to have Visual Studio 2 0 1 0 Professional installed, with (obviously) the Visual F# feature set installed with it If you have a Visual Studio 2 0 0 8 installation, you can still play in the F# playground, but it's a bit harder: You must find and download the Visual F# install bits for... code available for this book and all other Wrox books ERRATA We make every effort to ensure that there are no errors in the text or in the code However, no one is perfect, and mistakes do occur If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback By sending in errata, you may save another reader hours of frustration, and... Subscribe to this Forum icon by the forum name in the forum listing For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books To read the FAQs, click the FAQ link on any P2P page www.it-ebooks.info PART O Beginnings • CHAPTER 1: Primer www.it-ebooks.info 1 Primer... only the F# language compiler and nothing else — no ASP.NET, no Silverlight, nothing (As of this writing, the F# team was exploring whether the Visual Studio 2010 Shell would work as a host for the F# 2 0 bits, and while it's likely that such a combination will work, none of the authors here can verify that for a fact.) If you are looking to use F# on Mono, then you want to download the "F# 2 0 for Mono/Mac/... there As of this writing, the "F# Downloads" page on Microsoft Research ( r e s e a r c h m i c r o s o f t c o m ) has links to all of the different flavors discussed here Our assumption is that the vast majority of our readership will be using Visual Studio 2 0 1 0 or Visual Studio 2 0 0 8 , so if you're one of the readers outside of that population set, we apologize www.it-ebooks.info INTRODUCTION... that So this chapter focuses primarily on the syntax, and how F# "does objects" both similarly to, and differently from, its sibling languages C# and Visual Basic Part III takes on an entirely different tone, that of Functions, and will be the new material and concepts for most readers Instead of using Visual Studio, you use the REPL (Read-Evaluate-PrintLoop) for writing snippets of code and seeing them... but you won't find mind-popping concepts in here If it seems way too difficult, then don't despair — that chapter is intended as a microcosm of where we want you to end up If that chapter seems "just right," though, head on over to the register WHAT THIS BOOK COVERS This book takes a four-part approach to the F# language (officially, the F# 2 0 version of the language): basics, objects, functions, and... work with both functions and objects, in some kind of pleasant harmony, on top of the CLR If you're still not sure if you're the right reader for this book, take this little test: read Chapter 1, Primer, and see if that makes sense to you If it seems way too simple, you're probably more functionally-minded than we assumed the average reader to be; you'll find the book useful as a reference, perhaps,... "object-trained") developer will find most useful Part 0 is the Primer, a gentle up-sloping introduction to the concepts that the F# language incorporates as first-class citizens as well as a hint of some of the ways in which functional programming can be useful within the N E T environment Part I covers Basics Here, you'll find definitions of the primitive types, flow control, syntax rules, and other . Attributes 20 2 Creation and Consumption 20 3 Creation 20 3 Consumption 20 5 Summary 20 6 CHAPTER 13: FUNCTIONS 20 9 Traditional Function Calls 20 9 Mathematical Functions 21 0 Coming from C# 21 1 Function. Conditional 20 0 ParamArray 20 0 Struct, Class, AbstractClass, Interface, Literal, and Measure 20 1 Assembly Attributes 20 1 DefaultMember 20 2 Serializable, NonSerialized 20 2 AutoOpen 20 2 Other. Functions at Runtime 22 1 Summary 22 3 CHAPTER 14: IMMUTABLE DATA 22 5 The Problem with State 22 5 State Safety 22 6 Programwide State Safety 22 6 Local Data State Safety 22 9 Data Mutation 23 2