ebook img

Functional Programming in Swift PDF

212 Pages·2014·0.596 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Functional Programming in Swift

Chris Eidhof, Florian Kugler, and Wouter Swierstra Contents 1 Introduction 1 UpdatestotheBook . . . . . . . . . . . . . . . . . . . . . . 3 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 3 2 ThinkingFunctionally 5 Example:Battleship . . . . . . . . . . . . . . . . . . . . . . 5 First-ClassFunctions . . . . . . . . . . . . . . . . . . . . . . 11 Type-DrivenDevelopment. . . . . . . . . . . . . . . . . . . . 16 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3 WrappingCoreImage 18 TheFilterType . . . . . . . . . . . . . . . . . . . . . . . . . 19 BuildingFilters . . . . . . . . . . . . . . . . . . . . . . . . . 19 ComposingFilters. . . . . . . . . . . . . . . . . . . . . . . . 22 TheoreticalBackground:Currying. . . . . . . . . . . . . . . . 24 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 4 Map,Filter,Reduce 27 IntroducingGenerics . . . . . . . . . . . . . . . . . . . . . . 27 Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 PuttingItAllTogether . . . . . . . . . . . . . . . . . . . . . . 36 Genericsvs.theAnyType . . . . . . . . . . . . . . . . . . . . 37 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5 Optionals 41 CaseStudy:Dictionaries . . . . . . . . . . . . . . . . . . . . 41 CombiningOptionalValues . . . . . . . . . . . . . . . . . . . 45 WhyOptionals? . . . . . . . . . . . . . . . . . . . . . . . . . 50 6 QuickCheck 54 BuildingQuickCheck . . . . . . . . . . . . . . . . . . . . . . 56 MakingValuesSmaller . . . . . . . . . . . . . . . . . . . . . 60 ArbitraryArrays . . . . . . . . . . . . . . . . . . . . . . . . . 62 UsingQuickCheck . . . . . . . . . . . . . . . . . . . . . . . . 66 NextSteps . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 7 TheValueofImmutability 69 VariablesandReferences . . . . . . . . . . . . . . . . . . . . 69 ValueTypesvs.ReferenceTypes . . . . . . . . . . . . . . . . 70 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 8 Enumerations 78 IntroducingEnumerations . . . . . . . . . . . . . . . . . . . 78 AssociatedValues . . . . . . . . . . . . . . . . . . . . . . . 81 AddingGenerics . . . . . . . . . . . . . . . . . . . . . . . . 84 OptionalsRevisited . . . . . . . . . . . . . . . . . . . . . . . 86 TheAlgebraofDataTypes. . . . . . . . . . . . . . . . . . . . 87 WhyUseEnumerations? . . . . . . . . . . . . . . . . . . . . 89 9 PurelyFunctionalDataStructures 90 BinarySearchTrees. . . . . . . . . . . . . . . . . . . . . . . 90 AutocompletionUsingTries . . . . . . . . . . . . . . . . . . . 96 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 10Diagrams 103 DrawingSquaresandCircles . . . . . . . . . . . . . . . . . . 103 TheCoreDataStructures . . . . . . . . . . . . . . . . . . . . 107 CalculatingandDrawing . . . . . . . . . . . . . . . . . . . . 110 CreatingViewsandPDFs . . . . . . . . . . . . . . . . . . . . 114 ExtraCombinators . . . . . . . . . . . . . . . . . . . . . . . 115 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 11GeneratorsandSequences 119 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 CaseStudy:TraversingaBinaryTree . . . . . . . . . . . . . . 128 CaseStudy:BetterShrinkinginQuickCheck . . . . . . . . . . 130 BeyondMapandFilter . . . . . . . . . . . . . . . . . . . . . 134 12ParserCombinators 138 TheCore . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 ConvenienceCombinators . . . . . . . . . . . . . . . . . . . 149 ASimpleCalculator . . . . . . . . . . . . . . . . . . . . . . . 152 13CaseStudy:BuildingaSpreadsheetApplication 157 SampleCode . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 TheGUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 14Functors,ApplicativeFunctors,andMonads 179 Functors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 ApplicativeFunctors . . . . . . . . . . . . . . . . . . . . . . 181 TheM-Word. . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 15Conclusion 190 FurtherReading. . . . . . . . . . . . . . . . . . . . . . . . . 190 WhatisFunctionalProgramming?. . . . . . . . . . . . . . . . 192 Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 AdditionalCode 194 StandardLibrary . . . . . . . . . . . . . . . . . . . . . . . . 194 Chapter6,QuickCheck . . . . . . . . . . . . . . . . . . . . . 196 Chapter10,Diagrams . . . . . . . . . . . . . . . . . . . . . . 197 Chapter11,Generators . . . . . . . . . . . . . . . . . . . . . 200 Chapter12,ParserCombinators . . . . . . . . . . . . . . . . 201 References 205 Chapter1 Introduction Whywritethisbook? ThereisplentyofdocumentationonSwiftreadily availablefromApple,andtherearemanymorebooksontheway. Why doestheworldneedyetanotherbookonyetanotherprogramminglan- guage? Thisbooktriestoteachyoutothinkfunctionally.WebelievethatSwift hastherightlanguagefeaturestoteachyouhowtowritefunctionalpro- grams. Butwhatmakesaprogramfunctional? Andwhybotherlearning aboutthisinthefirstplace? Itishardtogiveaprecisedefinitionoffunctionalprogramming—in thesameway,itishardtogiveaprecisedefinitionofobject-orientedpro- gramming,oranyotherprogrammingparadigmforthatmatter. Instead, wewilltrytofocusonsomeofthequalitiesthatwebelievewell-designed functionalprogramsinSwiftshouldexhibit: • Modularity: Ratherthanthinkingofaprogramasasequenceof assignments and method calls, functional programmers empha- sizethateachprogramcanberepeatedlybrokenintosmallerand smallerpieces;allthesepiecescanbeassembledusingfunction applicationtodefineacompleteprogram. Ofcourse,thisdecom- positionofalargeprogramintosmallerpiecesonlyworksifwe canavoidsharingstatebetweentheindividualcomponents. This bringsustoournextpoint. • ACarefulTreatmentofMutableState: Functionalprogrammingis sometimes(half-jokingly)referredtoas‘value-orientedprogram- ming.’ Object-oriented programming focuses on the design of classesandobjects,eachwiththeirownencapsulatedstate.Func- tionalprogramming,ontheotherhand,emphasizestheimportance ofprogrammingwithvalues,freeofmutablestateorothersideef- fects.Byavoidingmutablestate,functionalprogramscanbemore easilycombinedthantheirimperativeorobject-orientedcounter- parts. • Types: Finally,awell-designedfunctionalprogrammakescareful useoftypes.Morethananythingelse,acarefulchoiceofthetypes ofyourdataandfunctionswillhelpstructureyourcode.Swifthas apowerfultypesystemthat,whenusedeffectively,canmakeyour codebothsaferandmorerobust. WefeelthesearethekeyinsightsthatSwiftprogrammersmaylearnfrom thefunctionalprogrammingcommunity.Throughoutthisbook,wewillil- lustrateeachofthesepointswithmanyexamplesandcasestudies. Inourexperience,learningtothinkfunctionallyisnoteasy. Itchal- lengesthewaywe’vebeentrainedtodecomposeproblems.Forprogram- merswhoareusedtowritingforloops,recursioncanbeconfusing;the lackofassignmentstatementsandglobalstateiscrippling;andclosures, generics,higher-orderfunctions,andmonadsarejustplainweird. Throughoutthisbook,wewillassumethatyouhavepreviousprogram- mingexperienceinObjective-C(orsomeotherobject-orientedlanguage). Wewon’tcoverSwiftbasicsorteachyoutosetupyourfirstXcodeproject, butwewilltrytorefertoexistingAppledocumentationwhenappropriate. YoushouldbecomfortablereadingSwiftprogramsandfamiliarwithcom- monprogrammingconcepts,suchasclasses,methods,andvariables.If you’veonlyjuststartedtolearntoprogram,thismaynotbetherightbook foryou. Inthisbook,wewanttodemystifyfunctionalprogramminganddispel someoftheprejudicespeoplemayhaveagainstit.Youdon’tneedtohave aPhDinmathematicstousetheseideastoimproveyourcode!Functional programmingisnottheonlywaytoprograminSwift.Instead,webelieve thatlearningaboutfunctionalprogrammingaddsanimportantnewtool toyourtoolboxthatwillmakeyouabetterdeveloperinanylanguage. UpdatestotheBook AsSwiftevolves,we’llcontinuetomakeupdatesandenhancementsto thisbook. Shouldyouencounteranymistakes, orifyouwouldliketo sendanyotherkindoffeedbackourway,pleasefileanissueinourGitHub repository. Acknowledgements We’dliketothankthenumerouspeoplewhohelpedshapethisbook.We wantedtoexplicitlymentionsomeofthem: NatalyeChildressisourcopyeditor.Shehasprovidedinvaluablefeed- back,notonlymakingsurethelanguageiscorrectandconsistent,but alsomakingsurethingsareunderstandable. SarahLincolndesignedthecoverandgaveusfeedbackonthedesign andlayoutofthebook. WouterwouldliketothankUtrechtUniversityforlettinghimtaketime toworkonthisbook. Wewouldliketothankthebetareadersfortheirfeedbackduringthe writingofthisbook(listedinalphabeticalorder): Adrian Kosmaczewski, Alexander Altman, Andrew Halls, Bang Jun- young, Daniel Eggert, Daniel Steinberg, David Hart, David Owens II, Eugene Dorfman, f-dz-v, Henry Stamerjohann, J Bucaran, Jamie For- rest,JaromirSiska,JasonLarsen,JesseArmand,JohnGallagher,Kaan Dedeoglu,KareMorstol,KielGillard,KristopherJohnson,MatteoPiombo, NicholasOutram,OleBegemann,RobNapier,RonaldMannak,SamIsaac- son,SsuJenLu,StephenHorne,TJ,TerryLewis,TimBrooks,VadimSh- pakovski. Chris,Florian,andWouter Chapter2 ThinkingFunctionally FunctionsinSwiftarefirst-classvalues,i.e.functionsmaybepassedas argumentstootherfunctions,andfunctionsmayreturnnewfunctions. Thisideamayseemstrangeifyou’reusedtoworkingwithsimpletypes, suchasintegers,booleans,orstructs. Inthischapter,wewilltrytoex- plainwhyfirst-classfunctionsareusefulandprovideourfirstexampleof functionalprogramminginaction. Example:Battleship We’llintroducefirst-classfunctionsusingasmallexample:anon-trivial functionthatyoumightneedtoimplementifyouwerewritingaBattleship- likegame.Theproblemwe’lllookatboilsdowntodeterminingwhetheror notagivenpointisinrange,withoutbeingtooclosetofriendlyshipsorto us. Asafirstapproximation,youmightwriteaverysimplefunctionthat checkswhetherornotapointisinrange. Forthesakeofsimplicity,we willassumethatourshipislocatedattheorigin. Wecanvisualizethe regionwewanttodescribeinFigure2.1. Thefirstfunctionwewrite,inRange1,checksthatapointisinthegrey

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.