768 Professional F# 2.0 free download ebook

Join the discussion

@

Wrox P r o g r a m m e r to P r o g r a m m e r 7

p2p.w rox.com

asm.

Foreword by Scott H anselman, Program

M anager,

M icrosoft

Ted New ard , A aro n C. Eriekso n, Talbo tt Cro w ell, Richard M inerich

www.it-ebooks.info

PROFESSIONAL F# 2.0

FOREWORDzyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA

xxiii

INTRODUCTION



PARTO

BEGINNINGS

CHAPTER 1

Primer



BASICS


PARTI

xxi

3

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



OBJECTS


PART II

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




FUNCTIONAL PROGRAMMING

PART III

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 18zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA
C#

283

CHAPTER 19

Databases

297

CHAPTER 2 0

XML

317


CHAPTER 21

ASP.NET MVC

341

CHAPTER 22

Silverlight

357

CHAPTER 23

Services

377

391


INDEX

www.it-ebooks.info

PROFESSIONAL

F# 2.0

Ted New ard
A aro n C. Erickso n
Talbo tt Cro w ell
Richard Minerich

WI LEY

W iley Publishing, Inc.

www.it-ebooks.info


Pr o f essi o n al F# 2 . 0
Published by
W iley Publishing, Inc.
10475 Cro ssp o int Bo ulev ard
Ind ianap o lis, IN 46256
w w w .w iley .co m
Co p yright © 2011 by W iley Publishing, Inc., Ind ianap o lis, Ind iana
Published simultaneo usly in Canad a
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)
M anufactured in the United States o f A merica
10 9 8 7 6 5 4 3 2 1
N o p art o f this p ublicatio n may be rep ro d uced , sto red in a retrieval system o r transmitted in any fo rm o r by any means,
electro nic, mechanical, p ho to co p y ing , reco rd ing , scanning o r o therw ise, excep t as p ermitted und er Sectio ns 107 o r 108
o f the 1976 United States Co p yright A ct, w itho ut either the p rio r w ritten p ermissio n o f the Publisher, o r autho rizatio n
thro ugh p ayment o f the ap p ro p riate p er-co p y fee to the Co p yright Clearance Center, 2 2 2 Ro sew o o d Driv e, Danv ers,
M A 01923, (978) 750- 8400, fax (978) 6 4 6 - 8 6 0 0 . Requests to the Publisher fo r p ermissio n sho uld be ad d ressed to the
Permissio ns Dep artm ent, Jo hn W iley & So ns, Inc., I l l Riv er Street, H o b o ken, N J 07030, (201) 748- 6011, fax (201)
748- 6008, o r o nline at h t t p : / / www. w i l e y . c o m / g o / p e r m i s s i o n s .
Limit o f Liability / Disclaimer o f W arranty : The publisher and the autho r make no rep resentatio ns o r w arranties w ith
resp ect to the accuracy o r co mp leteness o f the co ntents o f this w o rk and specifically d isclaim all w arranties, includ ing
w itho ut limitatio n w arranties o f fitness fo r a p articular p urp o se. N o w arranty may be created o r extend ed by sales o r p ro mo tio nal materials. The advice and strategies co ntained herein may no t be suitable fo r every situatio n. This w o rk is sold
w ith the und erstand ing that the publisher is no t engaged in rend ering legal, acco unting , o r o ther p ro fessio nal services.
If p ro fessio nal assistance is required , the services o f a co mp etent p ro fessio nal p erso n sho uld be so ught. N either the p ublisher no r the autho r shall be liable fo r d amages arising herefro m. The fact that an o rg aniz atio n o r W eb site is referred to
in this w o rk as a citatio n and/ or a p o tential so urce o f further info rmatio n d o es no t mean that the autho r o r the publisher
end o rses the info rmatio n the o rg aniz atio n o r W eb site may pro vid e o r reco mmend atio ns it may make. Further, read ers
sho uld be aw are that Internet W eb sites listed in this w o rk may have changed o r d isap p eared betw een w hen this w o rk w as
w ritten and w hen it is read .
Fo r general info rmatio n o n o ur o ther p ro d ucts and services p lease co ntact o ur Custo mer Care D ep artm ent w ithin the
United States at (877) 762- 2974, o utsid e the United States at (317) 572- 3993 o r fax (317) 5 7 2 - 4 0 0 2 .
W iley also publishes its bo o ks in a v ariety o f electro nic fo rmats. So me co ntent that ap p ears in p rint may no t be av ailable
in electro nic b o o ks.
Library o f Co ngress Co ntro l N um ber: 2010932419
Trad em arks: W iley, the W iley lo go , W ro x, the W ro x lo go , Pro g rammer to Pro g rammer, and related trad e d ress are trad em arks o r registered trad emarks o f Jo hn W iley & So ns, Inc. and/ or its affiliates, in the United States and o ther co untries,
and may no t be used w itho ut w ritten p ermissio n. A ll o ther trad emarks are the p ro p erty o f their respective o w ners. W iley
Publishing, Inc., is no t asso ciated w ith any p ro d uct o r vend o r mentio ned in this b o o k.

www.it-ebooks.info

To Charlotte: thank you.
— T ED N EW A R D

For my grandmother

who gave me confidence

to write,

and for my kids for giving me a reason to.
— A A R O N C . ER IC K SO N

This book is dedicated

to my family.

— T A L BO T T C R O W EL L

To Lou Franco, beyond being a mentor and friend,
you showed me that tuhat I once thought hard tuas in
fact easy.
— RIC H A RD

www.it-ebooks.info

M IN ER IC H

CREDITS

ACQUISITIONS EDITOR
Paul Reese

VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER
Richard S w a d l e y

DEVELOPMENT EDITOR
Kelly Talbot

VICE PRESIDENT AND
EXECUTIVE PUBLISHER

TECHNICAL EDITORS

Barry Pruett

Jason Mauer
Matthew Podwysockl

ASSOCIATE PUBLISHER

Al S c h e r e r
David M o r t o n

Jim M l n a t e l
PROJECT COORDINATOR, COVER

PRODUCTION EDITOR

Lynsey S t a n f o r d

Rebecca Anderson
PROOFREADER
COPY EDITOR

Shellah L e d w l d g e ,

San D e e Phillips

Word O n e N e w York

EDITORIAL DIRECTOR

INDEXER

R o b y n B. S l e s k y

J o h n n a V a n H o o s e Dlnse

EDITORIAL MANAGER

COVER DESIGNER

Mary Beth Wakefield

M i c h a e l E. Trent

PRODUCTION MANAGER

COVER PHOTO

Tim Tate

© hfng/lstockphoto.com

www.it-ebooks.info

ABOUT THE AUTHORS

TED NEWARDzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
is the Princip al w ith N ew ard & A sso ciates, a co nsulting firm that w o rks w ith clients
o f all sizes, fro m Fo rtune 500s to small startup s. He is fascinated w ith p ro g ramming languages,
v irtual machines, and enterp rise-class systems, spends a lo t o f his time in the Jav a and .N ET eco systems, and has recently begun to exp lo re the w o rld o f mo bile devices and games. He resides w ith his
w ife, tw o so ns, and eight lap to p s in the Pacific N o rthw est.
AARON C. ERICKSON is a Princip al Co nsultant w ith Tho ug htW o rks. H is life's w o rk is helping
o rg aniz atio ns better leverage techno lo g y by co ntributing to so lutio ns that have substantial po sitive
eco no m ic imp act fo r his clients. He is an enthusiast o f agile techniques fo r delivery o f so ftw are, and
he has a special interest in helping co mp anies und erstand ho w to leverage functio nal p ro g ramming
techniques to p erfo rm meaning ful business analy tics, p articularly using natural language p ro cessing
and M o nte Carlo simulatio n.
TALBOTT CROWELL is a So lutio n A rchitect and fo und er o f Th ird M respo nsible fo r d esigning and
build ing enterprise ap p licatio ns w ith a fo cus o n M ic ro so ft techno lo g ies includ ing SharePo int,
BizTalk Server, and the .N ET framew o rk. His co mp any delivers so lutio ns and services to large
and small co mp anies, includ ing Fo rtune 500s. Th ird M also assists co mp anies w ith the develo pment p ro cess by using a blend o f A gile and trad itio nal metho d o lo g ies, Team Fo und atio n Server and
Visual Stud io Team System, Scrum, Test Driven Dev elo p ment (TD D ), p erfo rmance testing, and
o ther pro ven to o ls and p ractices. Invo lved in the develo per co mmunity , Talbo tt co -fo und ed the F#
User Gro up ,zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
http: //fsug.org, and serves as a lead fo r o ther co m m unity events and gro ups such
as SharePo int Saturd ay Bo sto n and the Bo sto n A rea SharePo int User Gro up . Yo u can fo llo w him o n
tw itter, @ talb o tt, o r http: //twitter, com/talbott.
RICHARD MINERICH began to no tice a p ro blem in the so ftw are ind ustry o nly a few years after grad uating fro m UM ass A mherst. He saw a deep divide betw een the remarkable ad v ancements being
mad e in co mp uter science and the aged to o ls still in use by so ftw are engineers and d o main exp erts.
Thro ug h w riting , sp eaking, and co nsulting , Richard ho p es to bring these ad vances to a bro ad er
aud ience, to facilitate the creatio n o f intelligent so ftw are, and to bring disruptive change to stagnant
ind ustries. Richard is currently a M ic ro so ft M V P fo r the F# p ro g ramming language and is o ne o f
three lead ers o f the N ew Eng land F# User Gro up .

www.it-ebooks.info

ACKNOWLEDGMENTS

FIRST AND FOREMOST, IzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
w ould like to thank A aro n, Rick, and Talbo tt fo r sw ooping in at the last
seco nd, carving o ff chunks o f the vastly-overw helming " T O D O " list remaining to me, and kno cking them o ff w ith nary a co mplaint o r challenge. Yo u guys have been a delight to w o rk w ith. A tip
o f the hat must also go to Do n Syme, Luke Ho ban, Chris Smith, and the o thers on the F# team,
w ho patiently answ ered stupid question after stupid questio n. Thanks must also go out to the various attendees w ho 've listened to me prattle on about F# , bo th tho se w ho knew mo re abo ut the
subject than I, as w ell as tho se w ho knew less — all o f you have been extremely helpful in ho ning
the delivery o f the answ er to the questio n, "W hat is F# , w hy do I care, and ho w do I use it?" M att
Po d w yso cki in particular gets a hearty kudo for helping me understand some o f the tho rnier functio nal co ncepts, and Kevin Hazzard gets one just fo r being himself.
Lastly, no bo o k gets w ritten w itho ut a support structure, and in this case, that structure co nsists
principally o f my w ife, Charlo tte, w ho patiently endured night after night o f "I promise I'll be ho me
by mid night" and w ound up w aiting for me 'til 3 o r 4 A M , just to hear ho w my day (er... night)
w ent. Ho n, you deserved much better than me, but I'll never tell, on the o ff chance that you haven't
figured it out yet.
— T ED N EW A R D

I WOULD LIKE TO thank, my w ife, my kid s, and my pro fessio nal co lleagues for their support thro ugh
this pro cess. O f co urse, a hearty thanks goes to the fo lks at W ro x w ho have been very patient along
the way, especially during tho se times w here billable co nsulting time co nflicted w ith bo o k w riting
time. O f co urse, w itho ut all the great people in the F# co mmunity, this bo o k w ould not have happened. Particular thanks goes to A lex Pedenko , w ho helped me vet the Relatio nal Reco rd Map p er
co ncept, nicely extend ing the w o rk I started in the data chapter.
— A A R O N C . ER IC K SO N

www.it-ebooks.info

ACKNOWLEDGMENTS

I WOULD LIKE TOzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
thank my family, especially my w ife Pradeepa and tw o sons, Tristan and W illiam,
for their support and patience w hile I w orked on this bo o k. I w ould also like to thank my parents
and siblings w ho have also been majo r supporting facto rs in my life. I w ould like to extend my gratitude to w ard my co -autho rs, Ted N ew ard , A aro n Erickso n, and Rick Minerich for their dedication
to getting this bo o k published, Michael de la M az a for spearheading the F# User Gro up, Do n Syme
and M icro so ft Research for their brilliant w o rk creating F#, plus Luke Ho ban and the M icro so ft
pro duct team for bringing F# into Visual Studio as part o f the pro d uct.
— T A L BO T T C R O W EL L

NO AMOUNT OF THANKS to my co -autho rs w ould be eno ugh. Ted, for bringing vision and leadership
to this p ro ject. A aro n, for his frequent advice on dealing w ith the many small dramas o f the autho ring and co nsulting w o rld. Talbo tt, for reco mmend ing me for this pro ject and for being my N ew
England F# bro ther-in-arms. I'd also like to thank Michael de la M az a w ho came up w ith the idea
to start a N ew England F# User Gro up, everyone at A talaso ft fo r supporting me in this and my parents fo r cheering me up w hen the pressures seemed w o rst. Finally, I'd like to thank the F# co mmunity; each o f you proves the superiority o f statically-typed functio nal pro gramming on a daily basis.
— RIC H A RD

www.it-ebooks.info

M IN ER IC H

CONTENTS

FOREWORD

xxi

INTRODUCTION

xxiii

CHAPTER 1: PRIMER

3

Setup
It's that Time of Year Again...
Strategy
The Delegate Strategy
Lambda Calculus (Briefly)
Type Inference
Immutability
Expressions, not Statements
Summary

CHAPTER 2: LEXICAL STRUCTURE
Comments
Identifiers
Preprocessor Directives
Significant Whitespace
Summary

5
7
10
12
17
22
26
27
28

31
31
32
33
34
35

CHAPTER 3: PRIMITIVE TYPES

37

Boolean
Numeric Types
Bitwise Operations
Floating-Point Types
Arithmetic Conversions
String and Character Types
Unit
Units of Measure Types

37
38
40
40
41
42
43
43

www.it-ebooks.info

CONTENTS

Literal Values
Summary

44
45

CHAPTER 4: CONTROL FLOW
Basic Decisions: if
Looping: while/do
Looping: for
Exceptions

47
47
49
50
50

try...with

51

try...finally

52

Raising a n d T h r o w i n g Exceptions

52

Defining N e w Exception Types

Summary

53

53

CHAPTER 5: COMPOSITE TYPES
Option Types

55
55

O p t i o n Functions

57

Tuples
Arrays

58
60

Array C o n s t r u c t i o n

60

Array Access

62

Array Functions

62

Lists

65

List C o n s t r u c t i o n

66

List Access

68

List M e t h o d s

70

Using Lists and Arrays
Sequences
Maps

72
74
79

Map C o n s t r u c t i o n

79

Map Access

80

Map Functions

81

Sets
Summary

82
83

CHAPTER 6: PATTERN MATCHING
Basics
Pattern Types

85
85
88

Constant Patterns

88

V a r i a b l e - B i n d i n g ( " N a m e d " ) Patterns

89

www.it-ebooks.info

CONTENTS

A N D , OR Patterns

90

Literal Patterns

90

Tuple Patterns

91

as Patterns

92

List Patterns

92

Array Patterns

93

Discriminated Union Patterns

93

Record Patterns

93

Pattern Guards
Active Patterns

94
95

Single Case

96

Partial Case

97

Multi-Case

99

Summary

102

I PART II: OBJECTS

I

CHAPTER 7: COMPLEX COMPOSITE TYPES
Type Abbreviations
Enum Types
Discriminated Union Types
Structs

105
105
106
109
114

Value Type Implicit M e m b e r s

117

Structs and Pattern-Matching

118

Record Types

119

Record Type Implicit M e m b e r s

Summary

123

123

CHAPTER 8: CLASSES

125

Basics

125

Fields

126

Constructors

127

Creating

131

Members

132

Properties

132

Methods

140

Static Members

146

Operator Overloading

147

Delegates and Events

149

Subscribing

150

Delegates

150

www.it-ebooks.info

CONTENTS

DelegateEvents

152

B e y o n d DelegateEvents: Events

Access Modifiers
Type Extensions
Summary

154

155
157
159

CHAPTER 9: INHERITANCE

161

Basics

161

Fields a n d C o n s t r u c t o r s

163

Overriding

166

Abstract Members

168

Default

169

Casting

171

Upcasting

172

Downcasting

172

Flexible Types

173

Boxing a n d U n b o x i n g

174

Interfaces

177

Implementation

177

Definition

180

Object Expressions
Summary

181
181

CHAPTER 10: GENERICS

183

Basics

183

Type Parameters

185

Type Constraints

186

Type Constraint

187

Equality Constraint

187

C o m p a r i s o n Constraint

188

Null Constraint

188

C o n s t r u c t o r Constraint

188

Value Type a n d Reference Type Constraints

188

Other Constraints

189

Statically Resolved Type Parameters
Explicit M e m b e r Constraint

Summary

189
189

190

CHAPTER 11: PACKAGING

191

Namespaces

191

Referencing a N a m e s p a c e

www.it-ebooks.info

191

CONTENTS

Defining a N a m e s p a c e

192

Modules

193

Referencing a M o d u l e

193

Defining a M o d u l e

193

Summary

195

CHAPTER 12: CUSTOM ATTRIBUTES
Using Custom Attributes

197
197

EntryPoint

198

Obsolete

199

Conditional

200

ParamArray

200

Struct, Class, AbstractClass, Interface, Literal, a n d M e a s u r e

201

Assembly Attributes

201

DefaultMember

202

Serializable, NonSerialized

202

AutoOpen

202

Other Attributes

202

Creation and Consumption

203

Creation

203

Consumption

205

Summary

206

CHAPTER 13: FUNCTIONS

209

Traditional Function Calls
Mathematical Functions
Coming from C#
Function Arguments and Return Values

209
210
211
211

A u t o m a t i c Generalization a n d Restriction

211

T h e inline K e y w o r d

212

Type A n n o t a t i o n s

213

Generics and Type Constraints

214

Statically Resolved Type Parameters

215

Partial Application

215

Currying

216

Restrictions on Functions a n d M e t h o d s

217

Functions as First Class

218

Recursive Functions

218

Higher O r d e r Functions

219

Storing Functions

221

www.it-ebooks.info

CONTENTS

Creating Functions at Runtime

Summary

221

223

CHAPTER 14: IMMUTABLE DATA
The Problem with State
State Safety

225
225
226

P r o g r a m w i d e State Safety
Local Data State Safety

226
229

Data Mutation

232

A v o i d i n g Mutation

233

Bubble and Assign

235

Reference Cells

236

Passing by Reference

238

M e s s a g e Passing

238

Performance Considerations
Lists

239
239

Arrays

242

Sequences

242

Tuples

243

Records

243

structs

243

Summary

245

CHAPTER 15: DATA TYPES

247

Ambiguously Typed Data
Failing Fast
Specificity

247
248
248

O p t i o n as an Example

249

Encapsulating State in Types

249

A v o i d i n g Exceptions

251

Data and State Flow

252

Recursively D e f i n e d Data Types

253

Summary

255

CHAPTER 16: LIST PROCESSING
Collection Abstractions
Module Functions
Collection Subsets

257
257
258
258

filter

259

partition

259

www.it-ebooks.info

CONTENTS

Element Transformations

260

map

260

choose

262

collect

262

Accumulators

263

reduce

264

fold

265

scan

266

Summary

267

CHAPTER 17: PIPELINING AND COMPOSITION
Basic Composition and Pipelining

269
269

Pipelining

270

Composition

272

Applying Pipelining and Composition
From Loops to Pipelining

275
276

From Pipelining to C o m p o s i t i o n

277

Advanced Composition

278

Summary

280

CHAPTER 18: C#

283

Overview
Calling C# Libraries from F#

283
284

Simple M e t h o d Calling Scenarios

284

C# Object Construction

285

F#, C#, and null

286

F# a n d C# M e t h o d s that E x p e c t Delegates

287

F# a n d C# Events

288

F# to C # S u m 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
Retrieving Data Using ADO.NET

297
298

Creating a Database C o n n e c t i o n

298

Reading Data

299

Filtering Data

300

Insert, Update, and Delete

F# and Object Relational Mapping
Introducing F# Active Record (FAR)
Reading Data

301

302
303
303

Q u e r y i n g Data

304

A d d i n g Data

304

U p d a t i n g Data

305

D e l e t i n g Data

305

W h a t Isn't S u p p o r t e d

306

Coming Soon

306

How FAR Works

306

Dependencies

306

Utility Routines

307

Table Creation

308

Q u e r y Processing

309

I m p l e m e n t a t i o n of O t h e r FOR O p e r a t i o n s

314

Summary

315

CHAPTER 20: XML

317

Overview
F# and LINQ-to-XML

317
318

Reading

318

Querying

320

Processing

322

Writing

325

Writing X M L to M e m o r y or O t h e r S t r e a m - B a s e d Resources

F# and XML DOM

325

325

Reading

326

Querying

327

Processing

328

Writing

329

F#, XML, and Active Patterns

329

Multi-case A c t i v e Patterns

330

www.it-ebooks.info

CONTENTS

Partial-Case A c t i v e Patterns

336

Summary

339

CHAPTER 21: ASP.NET MVC

341

Overview
FORECAST'R - The World's Simplest Weather
Forecast Site

341
342

Modeling the Domain

343

Creating a Repository

344

Creating t h e Controller

349

Creating S o m e V i e w Helpers

351

Creating t h e V i e w

352

Summary

355

CHAPTER 22: SILVERLIGHT

357

Overview

357

S o f t w a r e Runtime a n d D e v e l o p e r Requirements

Visual Studio Project Templates

359

360

T h e Silverlight A p p l i c a t i o n

361

T h e F# Silverlight Library

363

The Silverlight Toolkit

365

Line Charts a n d Area Charts

365

Designer Tools

366

Data Binding

368

Design T i m e Data Binding

368

Programmatic Data Binding

371

Calculating Moving Average
Putting It All Together
Summary

372
373
376

CHAPTER 23: SERVICES

377

Overview
An F#-Based Weather Service
T h e Service C o n t r a c t

377
378
378

Leveraging the Domain Model
Writing the Service Controller

380
381

Rendering W e a t h e r

381

H e l p i n g t h e S e r v i c e Controller

381

S e r v i c e Controller I m p l e m e n t a t i o n

382

www.it-ebooks.info

CONTENTS

Service I m p l e m e n t a t i o n

383

Implementing the Service Host

Consuming Services

383

385

G e n e r a t i n g a S e r v i c e Stub
Writing t h e S e r v i c e C o n s u m e r

Summary

385
388

390

INDEX

391

www.it-ebooks.info

FOREWORD

There's Left, Right, and there's Center. There's peanut butter, cho co late, and then there's peanut
butter cups. C#, Visual Basic...and now there's F#. There have always been effectively only tw o
choices for programmers that target .N ET, and for many that's been no choice at all. Take a lo o k
at F#. It's a functio nal language, to be clear, but it's also o bject-o riented and a bridge betw een tw o
w orlds. It's all the goodness o f a peanut butter cup, and more.
To many, F# feels new and dramatic. Its values are rooted not just in some o f the first programming
languages, but the lambda calculus itself. F# may feel new to you and me, but it's based on 80 years
o f deep mathematical pro o f and respected tho ught.
W hen the get-er-done programmer hears names like Scheme, O Caml, Haskell, Erlang, and F#,
these languages co njure up visions o f crazy-eyed computer scientists and bearded hermits. You can't
expect to really sell softw are w ritten in these languages any more than Jo hn Grisham can sell a legal
mystery w ritten in Latin, right? That's madness.
A ctually no t. F# needs to be a new to o l in your to o lbo x. Imagine not thinking abo ut variables
changing their value. Imagine no glo bal state and no side effects. Imagine not w o rrying abo ut
deadlocks and race co nditio ns because you aren't using any lo cks. Consider not just testing your
application but proving that it w o rks and being able to co unt on it.
F# reminds us that w riting stateful code in a procedural language for a machine that has 12 cores is,
w ell, freaking hard to get right. F# reminds the N ET programmer that there is life beyond the simply procedural. F# gives you this, and the familiarity o f the N ET runtime and Base Class Library
that you already know how to use. You can w rite F# not just w ith N E T on Windo w s, but also on
Xb o x 360, Silverlight, and M o no on Linux.
There's another way o f thinking out there and it's functio nal. Study this bo o k's take on F#. It's clear,
code-focused, realistic, and pragmatic. This is a real language that you can solve real problems w ith.
I hope you enjoy reading this bo o k as much as I did.
— SC O T T H A N S E L M A N

Principal Program

Manager

— Server and Tools Online -

www.it-ebooks.info

Lead

Microsoft

zyxwvutsrqp

INTRODUCTION

This is a bo o k on the F# programming language.
On the surface o f things, that is a no nsensical and/ or intuitively obvious statement, given the title
o f this bo o k. Ho w ever, despite the apparent redundancy in saying it aloud, the sentence above
elegantly describes w hat this bo o k is abo ut: We are no t attempting to teach developers how to
accomplish tasks fro m o ther languages in this o ne, nor are w e attempting to evangelize the language o r its feature set o r its use "o v er" o ther languages. We assume that you are reading this
bo o k because you have an interest in learning the F# language: its syntax, its semantics, its pros
and co ns, and its use in co ncert w ith o ther parts o f the .N ET eco system.

WHO THIS BOOK IS FOR
In order to keep to the core focus o f the bo o k, we assume that you, the reader, are a journeyman
.N ET developer, familiar w ith at least one o f the programming languages in the .N ET ecosystem: C#
or Visual Basic w ill be the most co mmo n language o f choice for those in the .N ET community — but
if you've learned C++/ CLI or even one o f the lesser-know n .N ET languages (IronPython or Iro nRuby,
perhaps, or even one o f the dozens or so o f "alternative" languages for the CLR), you'll still be able to
follow along w ithout to o much difficulty.
In particular, we assume that you're already co mfo rtable w ith concepts like assemblies, managed
co de, and executing on top o f a virtual machine, so none o f that ".N ET 101" to pical material
appears here, as it w ould be redundant to w hat you've already read in a beginning or intermediate C# or Visual Basic bo o k. You've probably used Reflectio n at some point in your career, and/
or X M L , W inFo rms, Windo w s Presentation Foundation (or its w eb-based successor, Silverlight),
Windo w s Co mmunicatio n Fo undatio n, w ith maybe a little database access thro w n in for good
measure.

In short, we assume that you've been developing in the .N ET environment for the past couple o f
years. If that's not you, you may w ant to start w ith one o f the introductory .N ET titles, such as zyxwvutsrqponml
Beginning C# 3.0 or Beginning Visual Basic 2010. For that reaso n, there are no "hand -ho ld ing"
steps found in a variety o f other bo o ks w hen it comes to creating Visual Studio Solution files or
creating new Pro jects; not only w ould those steps be useless to the journeyman .N ET developer
(not to mention somew hat insulting), but they are also useless to the F# developer w ho w ants to use
Mo no Develo p and the M o no implementation o f the Co mmo n Language Runtime for w riting and
executing F# code. Considering that F# has held full compatibility w ith M o no as a goal since its
inception, ignoring that crow d felt rude.
If you are o f the handful o f functio nal programmers w ho've been w orking in Haskell, Ocaml, M L,
or some Lisp-based derivative, you're probably not going to like this bo o k. We spend no time discussing monads, monoids, or catamo rphisms here, nor do we consider that a missing part o f the

www.it-ebooks.info

INTRODUCTION

bo o k that "w e just didn't have time to co v er;" the bo o k you w ant w ill be w ritten entirely differently
than this o ne, in a different style than this o ne, and pro bably by entirely different autho rs.
This bo o k assumes you are co mfo rtable w ith o bject-o rientatio n and w ant to start dow n the path o f
learning no t o nly how to pro gram w ith functio nal co ncepts, but that you w ant to w o rk w ith bo th
functio ns and o bjects, in some kind o f pleasant harmo ny, on to p o f the C LR.
If you're still no t sure if you're the right reader for this bo o k, take this little test: read Chapter 1,
Primer, and see if that makes sense to you. If it seems w ay to o simple, you're pro bably more functio nally-minded than we assumed the average reader to be; you'll find the bo o k useful as a reference,
perhaps, o r as a skimmable guide to the syntax, but you w o n't find mind-po pping co ncepts in here.
If it seems w ay to o difficult, then don't despair — that chapter is intended as a micro co sm o f w here
we w ant you to end up.
If that chapter seems "just right," tho ugh, head on over to the register.

WHAT THIS BOOK COVERS
This bo o k takes a fo ur-part appro ach to the F# language (officially, the F# 2.0 version o f the language): basics, o bjects, functio ns, and "integratio n" (meaning ho w F# interacts w ith vario us .N ET
techno lo gies like Silverlight o r relatio nal databases). We go over the 9 0 % o f the F# pro gramming
language that w e think you're going to need.
No te that w e're not a complete reference on the language. We ignore the 10% o f the language specification that w e think most N E T developers w ill never run into , on the grounds that if you do run into
one o f tho se edge-case co nstructs, you'll have enough familiarity w ith the F# syntax to figure it o ut, or
you'll lo o k it up in the F# 2.0 Language Reference (or ask somebody in fo rums o r on a mailing list) for
the exact details. (Our guess is that it'll be at least a year o r so as a practicing F# developer before you
run into one o f those co nstructs.)

HOW THIS BOOK IS STRUCTURED
The bo o k is arranged in, we think, the order a practicing N E T (w hich means, "o bject-trained ")
developer w ill find mo st useful.
Part 0 is the Primer, a gentle up-sloping intro d uctio n to the co ncepts that the F# language inco rp o rates as first-class citizens as w ell as a hint o f some o f the w ays in w hich functio nal pro gramming
can be useful w ithin the N E T enviro nment.
Part I covers Basics. Here, you'll find definitions o f the primitive types, flow co ntro l, syntax rules,
and o ther such things that have to be defined befo re anything else can be discussed.
Part II covers O bjects. F# permits the creatio n o f new classes, interfaces and o ther o bject-o riented
types, as w ell as the trad itio nal set o f o bject-o riented features such as implementatio n inheritance,
and they're all covered here. In keeping w ith the to ne o f the bo o k, we don't spend a lot o f time

www.it-ebooks.info

INTRODUCTION

teaching you w hat "IS-A " means; as a practicing .N ET developer, you already kno w that. So this
chapter fo cuses primarily on the syntax, and ho w F# "d o es o bjects" bo th similarly to , and differently fro m, its sibling languages C# and Visual Basic.
Part III takes on an entirely different to ne, that o f Functio ns, and w ill be the new material and
co ncepts for mo st readers. Instead o f using Visual Studio, you use the REPL (Read -Evaluate-PrintLo o p) fo r w riting snippets o f code and seeing them execute immediately. Instead o f building up
o bjects, you create functio ns. A nd so o n. Read ers could stop after the end o f Part II and have F# as
"a better C# ," but doing so w ould be missing out on some o f the very things that make F# vastly
more interesting than C# .

Part IV, then, show s how to use F# w ith a variety o f different technologies ( X M L, Silverlight, services,
and so on), and tries to show one w ay — notzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLJIHGFEDC
the w ay — to use F# beyond straight console-mode applicatio ns. A s tempting as it might be to jump straight here and cut-and-paste the code into your ow n
applications, resist the urge until you've read thro ugh the first three parts. It's vastly more satisfying to
be able to predict w hat the code w ill lo o k like as you read along, than to just see the code execute and
have no real idea why.

WHAT YOU NEED TO USE THIS BOOK
We assume that you have Visual Stud io 2010 installed on your system. A s o f this w riting, unfo rtunately, no "Visual 2010 F# Exp ress" ed itio n d o w nlo ad exists fro m M icro so ft, so yo u'll need to
have Visual Stud io 2010 Pro fessio nal installed , w ith (obviously) the Visual F# feature set installed
w ith it.
If you have a Visual Studio 2008 installatio n, you can still play in the F# playgro und, but it's a bit
harder: Yo u must find and do w nlo ad the Visual F# install bits for Visual Studio 2008 (it's a Visual
Studio package), and install them. Technically, this is the "F# 2.0 fo r W ind o w s + Visual Studio
2008 (A pril 2010 release)" version.
If you don't have any version o f Visual Studio and are unw illing to acquire o ne, ano ther o ptio n is
available to you: a self-co nstructed version o f "Visual F# Exp ress." By installing the Visual Studio
2008 Shell and the afo rementio ned "F# 2.0 for W ind o w s..." bits, you w ill have a version o f Visual
Studio 2008 that co ntains o nly the F# language co mpiler and no thing else — no A SP.N ET, no
Silverlight, no thing. (As o f this w riting, the F# team w as explo ring w hether the Visual Studio 2010
Shell w ould w o rk as a ho st for the F# 2.0 bits, and w hile it's likely that such a co mbinatio n w ill
w o rk, none o f the autho rs here can verify that for a fact.)
If you are lo o king to use F# on M o no , then you w ant to dow nload the "F# 2.0 fo r Mono/ Mac/
Linux (compiler binaries)" and install acco rding to the instructio ns there.
A s o f this w riting, the "F# Do w nlo ad s" page on M icro so ft Research
has links to all o f the different flavors discussed here.

( re s e arc h . m i c ro s o f t. c o m )

O ur assumptio n is that the vast majo rity o f o ur readership w ill be using Visual Studio 2010 o r
Visual Studio 2008, so if you're one o f the readers outside o f that po pulatio n set, w e apologize

www.it-ebooks.info

INTRODUCTION

ahead o f time for w hatever conflicts you w ill find w ith command-prompt output, screen shots, or
references to IDE instructio ns.

CONVENTIONS
To help you get the most from the text and keep track o f w hat's happening, w e've used a number o f
conventions thro ugho ut the bo o k.

Boxes with a warning icon like this one hold important,
information
that is directly relevant to the surrounding

not-to-be-forgotten
text.

L
/ / ) The pencil icon indicates
—'
discussion.

notes, tips, hints, tricks, or asides to the

current

As for styles in the text:
We show keyboard strokes like this: Ctrl+A .
We show file names, URLs, and code w ithin the text like so: p e r s i s te n c e . p r o p e r ti e s .
We present code like this:

We use a monofont type for code examples.

SOURCE CODE
As you w ork thro ugh the examples in this bo o k, you may choose either to type in all the code manually, or to use the source code files that accompany the bo o k. A ll the source code used in this bo o k
is available for dow nload at www.wrox.com. W hen at the site, simply lo cate the bo o k's title (use the
Search bo x or one o f the title lists) and click the Do w nlo ad Code link on the bo o k's detail page to
o btain all the source code for the bo o k. Code that is included on the w ebsite is highlighted by the
follow ing icon:

Available for
download on
Wrox. com

www.it-ebooks.info

INTRODUCTION

Listings include the filename in the title. If it is just a code snippet, you'll find the filename in a code
note such as this:
Code snippet

filename

Because many books have similar titles, you may find it easiest to search
ISBN; this book's ISBN is
978-0-470-52801-3.

by

Once you dow nload the co de, just decompress it w ith your favorite compression to o l. A lternately,
you can go to the main W ro x code dow nload page at www.wrox. com/ dynamic/ books/ dow nload
. asp x to see the code available for this bo o k and all other W ro x bo o ks.

ERRATA
We make every effo rt to ensure that there are no errors in the text or in the code. How ever, no one
is perfect, and mistakes do o ccur. If you find an error in one o f our bo o ks, like a spelling mistake
or faulty piece o f code, we w ould be very grateful for your feedback. By sending in errata, you may
save another reader hours o f frustratio n, and at the same time, you w ill be helping us provide even
higher quality info rmatio n.
To find the errata page for this bo o k, go to www. w ro x. com and lo cate the title using the Search bo x
or one o f the title lists. Then, on the bo o k details page, click the Bo o k Errata link. On this page, you
can view all errata that has been submitted for this bo o k and posted by W ro x editors. A complete
bo o k list, including links to each bo o k's errata, is also available at w w w .w rox.com/ misc-pages/
b o o k l i s t. s h tm l .
If you don't spot "yo ur" error on the Bo o k Errata page, go to www.wrox. co m/ co ntact/ techsup p o rt
. shtml and complete the form there to send us the error you have found. We'll check the info rmatio n and, if appropriate, post a message to the bo o k's errata page and fix the problem in subsequent
editions o f the bo o k.

P2P.WROX.COM
For author and peer discussion, jo in the P2P forums at p 2p .w ro x.co m. The forums are a Web-based
system for you to post messages relating to W ro x bo o ks and related technologies and interact w ith
other readers and techno lo gy users. The forums offer a subscription feature to e-mail you topics
o f interest o f your choosing w hen new posts are made to the forums. W ro x authors, editors, other
industry experts, and your fellow readers are present on these forums.

www.it-ebooks.info

INTRODUCTION

At p 2p .w ro x.co m, you w ill find a number o f different fo rums that w ill help you, no t only as you
read this bo o k, but also as you develop your ow n applicatio ns. To jo in the fo rums, just follow
these steps:
1.

Go to p 2p . w ro x. com and click the Register link.

2.

Read the terms o f use and click Agree.

3.

Complete the required information to jo in, as well as any optional information you wish to
provide, and click Submit.

4.

Yo u w ill receive an e-mail w ith info rmatio n describing ho w to verify your acco unt and
complete the joining process.

You can read messages in the forums
your own messages, you must join.

without joining P2P, but in order to post

Once you jo in, you can post new messages and respond to messages other users po st. You can read
messages at any time on the Web. If you w ould like to have new messages from a particular forum
e-mailed to you, click the Subscribe to this Fo rum icon by the forum name in the forum listing.
For more info rmatio n about how to use the W ro x P2P, be sure to read the P2P FA Qs for answ ers to
questions about how the forum softw are w o rks, as w ell as many co mmo n questions specific to P2P
and W ro x bo o ks. To read the FA Qs, click the FAQ link on any P2P page.

www.it-ebooks.info

PART O
Beginnings
• CHAPTER 1:zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA
Primer

www.it-ebooks.info

1
Primer
WHAT'S IN THIS CHAPTER?
U n d e r s t a n d i n g strategies
Reviewing Lambda calculus
Infering types
>

U n d e r s t a n d i n g mutability

>

Creating your o w n bindings

Object-o riented programming has been w ith us for close to tw o decades, if not longer; its
expressions o f those concepts via the languages C# and Visual Basic, and the platform on
w hich they run, the C LR, have been more recent, only since 2002. The community and eco system around the o bject-o riented paradigm is vast, and the various traps and pitfalls around
an o bject-o riented way o f thinking has seen copious discussion and experience, and where
disagreements o ccur, reasoned and heated debate. From its inception more than 40 years
ago, through its explo ratio n in languages invented yesterday, an o bject-o riented approach to
languages has received the benefit o f the attention o f some o f the smartest language and to o l
designers in the industry, and a highly permutational approach to ancillary features around
the language, such as garbage co llectio n, strong-versus-w eak typing, compilation-versus-interpretation, and various hybrids thereo f, full-fidelity metadata, parameterized types, and more;
no stone, it seems, remains unturned.

One o f the principal goals o f an o bject-o riented language is the establishment o f user-defined
types (UDTs) that not only serve to capture the abstractio ns around the users' do main, but
also the capability to reuse those types in a variety o f different scenarios w ithin the same
domain w ithout mo dificatio n. Sometimes this domain is a business-flavored one — at the start
o f the 21st century these kinds o f types were called zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLJIHG
business objects and later domain
types.
Sometimes the domain is an infrastructural o ne, such as presentation or co mmunicatio n,

www.it-ebooks.info

4

I

CHAPTER 1

zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA
PRIMER

framework or class
and these types are frequently collected together in a large bundle know n as azyxwvutsrqponmlkjihgfedcbaZYXWVUTS
library. And despite the relatively slow start that C++ class libraries saw during C++'s heyday, the

co mbinatio n o f fast, cheap netw ork access and volunteers w illing to share their effo rts has led to a
proliferation o f these infrastructural bundles that dw arfs anything the industry has seen before.
Unfortunately, despite the huge success o f C++, Java, and .N ET, the o riginal premise o f the o bjectoriented, that developers could take o bjects "o ff the shelf" and reuse them w ithout mo dificatio n, has
yet to o ccur for anything but the infrastructural do main. Even in that domain, debate and duplicatio n rages over subtle points o f design that can only be changed by changing the underlying source
code making up those infrastructural types.
Mo re impo rtant, as the 20th century came to a close and the 21st loomed on the ho rizo n, developers
began to find "ed ges," limitations to the o bject-o riented paradigm that saw no easy answ er. These
edges pushed the o bject-o riented community to amend its approach slightly, placing those o bjects
into containers and relying on the co ntainer to provide a set o f services that could not easily be captured by o bject-o riented methodology. These component containers, exemplified by the Enterprise
Java Beans standard (and its later lighter-w eight successor, Spring) and COM+/ EnterpriseServices
found some tractio n but were never w holly adored by the developers w ho used them.
In time, those containers were amended to take a more co arse-grained approach, seeking a certain
degree o f simplification to enable for a more interoperable capacity, and these new domain bundles
received a new name: services. A lthough Service-Oriented A rchitecture (SOA ) sounded an entirely
new style o f pro gramming, developers seeking to take their traditio nal o bject-o riented concepts into
the service-oriented realm found themselves struggling w ith even the simplest o f designs.
Despite the guidance o f w ell-honed discussions around o bject-o riented design (called design patterns at first, then later just patterns), the more developers sought to model their softw are after the
reality o f the businesses around them, the more they struggled to achieve the reusability promised
them. Coupled w ith this came the disquieting realization that o bject languages had not only failed
to produce that set o f "Tinkerto y s" that developers or users could just reuse o ff the shelf, but also
that some domains defied some o f the modeling characteristics o f o bject languages entirely — some
domains were just complicated and aw kw ard to model in o bjects.
Then, subtly, a new problem emerged: the underlying hardw are ceased its steady march o f
improved perfo rmance and instead began to respond to the beat o f a different drum, that o f multicore. Suddenly, w here pro grammers used to face problems in a single- or slightly-multi-threaded
enviro nment, now the hardw are demanded that additional perfo rmance w ould come only from
greater and greater parallelizatio n o f code. W here the o bject-o riented developers o f the 20th century
could assume that only a single lo gical thread o f executio n w ould operate against their o bjects,
the developers o f the 21st century has to assume that many lo gical threads o f executio n w ill all be
hammering on their o bjects simultaneously. The implicatio n, that developers must now consider all
possible interactio ns o f multiple threads on every o peratio n available on the types they define, co ntinues to hang like a proverbial Sword o f Damo cles over the heads o f o bject-o riented pro grammers
even as the first decade o f the new century came to a clo se.
This chapter attempts to demonstrate some o f the technical challenges C# and Visual Basic developers (and, to a logical extent, their cousins and predecessors in Java and C++) have faced w hen
using the o bject-o riented paradigm exclusively. In the beginning, challenges w ill be addressed w ith

www.it-ebooks.info

Setup | 5

p ro gramming techniques available to the developer using o ff-the-shelf to o ls and techno lo gy, but as
the pro blems surmo unt, so w ill the desire to change tho se to o ls into so mething mo re, so mething that
d emo nstrates the need for a new appro ach to p ro gramming beyond the trad itio nal o bject-o riented o ne,
and a new language to exp lo re and exp o se tho se co ncep ts mo re succinctly and d irectly.

SETUP
Imag ine a system, a simple o ne (to start) fo r tracking stud ents and instructo rs and the classes they
teach. In keeping w ith trad itio nal o bject-o riented tho ug ht, several d o main typ es are d efined , here
in C # 2. 0, tho ug h the actual language — C# , Visual Basic, C++/ CLI (any . N ET language w o uld
w o rk) — in w hich they are defined m akes little d ifference:

class Person
{
private string m_first;
private string m_last;
private int m_age;
public Person(string fn, string In, int a)
{
FirstName = fn;
LastName = In;
Age = a;
}
public string FirstName
{

get { return m_first; }
set { m_first = value; }
}
public string LastName
{

get { return m_last; }
set { m_last = value; }
}
public int Age
{

get { return m_age; }
set { m_age = value; }
}
}

class Student : Person
{
private string m_major;
public Student(string fn, string In, int a, string maj)
: base(fn, In, a)
{
Maj or = maj;
}
public string Major

www.it-ebooks.info

6

I

CHAPTER 1

zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA
PRIMER

{

get { return m_major; }
set { m_major = value; }
}

class Instructor : Person
{
private string m_dept;
public Instructor(string fn, string In, int a, string dept)
: base(fn, In, a)
{
Department = dept;
}
public string Department
{
get { return m_dept; }
set { m_dept = value; }
}

class Class
{
private string m_name;
private List m_students = new List();
private Instructor m_instructor;
public Class(string n)
Name = n;
public string Name
get { return m_name; }
set { m_name = value; }
public Instructor Instructor
get { return m_instructor; }
set { m_instructor = value; }
public List Students
get { return m_students; }

A s w ith mo st systems o f its ty p e, the system begins simply: there are tw o kind s o f "Perso n"s in the
system, Students and Instructors, and Classes are taug ht to Students by Instructors. So ,
build ing up fro m basic p arts, lists o f Instructors and Students might lo o k like this:

class Program
{
static List Students = new List();

www.it-ebooks.info

It's That Time of Year Again-

static Program()
{
Instructors.Add(new Instructor("A1", "Scherer", 38,
"Computer Science"));
Instructors.Add(new Instructor("Albert", "Einstein", 50,
"Physics"));
Instructors.Add(new Instructor("Sigmund", "Freud", 50,
"Psychology"));
Instructors.Add(new Instructor("Aaron", "Erickson", 35,
"Underwater Basketweaving"));
Students.Add(new Student("Matthew", "Neward", 10,
"Grade school"));
Students.Add(new Student("Michael", "Neward", 16,
"Video game design"));
Students.Add(new Student("Charlotte", "Neward", 38,
"Psychology"));
Students.Add(new Student("Ted", "Neward", 39,
"Computer Science"));
}
}
Obvio usly, in a real-w o rld p ro g ram , these lists o f o bjects w ill be sto red in so me fo rm o f lo ng-term
sto rage, such as a relatio nal d atabase, but this suffices fo r no w .

IT'S THAT TIME OF YEAR AGAIN...
A t the beginning o f the scho o l year, new classes are created and entered into the system — again,
this is mo d eled in the examp le as a simple list:

List classesFor2010 = new List();
classesFor2010.Add(new Class("Scala for .NET Developers"));
classesFor2010.Add(new Class("F# for .NET Developers"));
classesFor2010.Add(new Class(
"How to play pranks on teachers"));
classesFor2010.Add(new Class(
"Baskets of the Lower Amazon"));
classesFor2010.Add(new Class("Child Psych"));
classesFor2010.Add(new Class("Geek Psych"));
A nd w hen the classes have been set up ( i n s t r u c t o r s w ill be assigned later, after the i n s t r u c t o r s
have d etermined w ho is lo w est o n the to tem po le and has to actually teach this year), the stud ents
need to lo g in to the system and register fo r classes:

Console.Write("Please enter your first name:");
string first = Console.ReadLine();
Console.Write("\nPlease enter your last name:");
string last = Console.ReadLine();
A fter the stud ent has entered this info rm atio n, the tw o strings must so meho w be reco nciled into a
s tu d e n t o b ject, a p ro cess that usually invo lves searching the list:

foreach (Student s in Students)

www.it-ebooks.info

8

I

CHAPTER 1

zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA
PRIMER

if (s.FirstName == first && s.LastName == last)
{
// ... Do something
}
}
This feels sloppy so meho w — after so me deeper tho ug ht, several things emerge as "w ro ng ."
First, an o bv io us bo ttleneck emerges if this list beco mes large; fo r a scho o l o f a half-d o zen

Instructors and a few do zen students, this simple o ne-at-a-time co mp ariso n w o rks w ell eno ugh,
but if the system gro w s to inco rp o rate camp uses all acro ss the w o rld and millio ns o f students,