ebook img

The Art of Functional Programming PDF

205 Pages·2022·4.668 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 The Art of Functional Programming

The Art of Functional Programming with examples in OCaml, Haskell, and Java Minh Quang Tran, PhD The Art of Functional Programming with examples in OCaml, Haskell, and Java Minh Quang Tran, PhD The Art of Functional Programming Copyright © 2022 Minh Quang Tran. All rights reserved. About the author: Minh Quang Tran has more than 20 years of experience studying so�ware development and working in the so�ware industry. He has worked in various tech startups and big so�ware companies in Europe. He received his M.Sc. in Computer Science from McMaster University, Canada, and his Ph.D. in Computer Science from Technical University of Berlin, Germany. His interest lies in understanding and mastering the fundamentals and principles that cut across programming languages, frameworks, and tools. Contents Contents 1 Introduction 3 1.1 AboutThisBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 ABiteofFunctionalProgramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 WhyFunctionalProgrammingMatters? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.4 RequiredTools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.5 QuizonImperativevs.FunctionalProgramming . . . . . . . . . . . . . . . . . . . . . . . 16 1.6 AnswerstoQuizonImperativevs.FunctionalProgramming . . . . . . . . . . . . . . . . . 17 2 Expressions–BuildingBlocksofFunctionalPrograms 18 2.1 FunctionalProgrammingisAllAboutExpressions . . . . . . . . . . . . . . . . . . . . . . 18 2.2 SyntaxofExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.3 ParsingExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.4 TypesofExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 2.5 ValuesofExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 2.6 AssignNamestoExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 2.7 ProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 2.8 SolutionstoProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 2.9 QuizonExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 2.10 AnswerstoQuizonExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 3 BuildingAbstractionswithFunctions 56 3.1 LambdaCalculus:FoundationofFunctionalProgramming . . . . . . . . . . . . . . . . . 56 3.2 FunctionAbstractionandFunctionApplication . . . . . . . . . . . . . . . . . . . . . . . . 60 3.3 UseCurryingforFunctionChaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 3.4 RecursiveFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 3.5 GeneralComputationMethodsasHigher-OrderFunctions . . . . . . . . . . . . . . . . . . 76 3.6 ProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 3.7 SolutionstoProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 3.8 QuizonFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 3.9 AnswerstoQuizonFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 4 CompoundDataTypes 93 4.1 GroupDataObjectsintoTuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 4.2 Destructtupleswithpatternmatching . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 TheArtofFunctionalProgramming 1 Contents 4.3 StoreSequencesofDatawithLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 4.4 DeclareUser-definedTypeswithAlgebraicDataTypes . . . . . . . . . . . . . . . . . . . . 103 4.5 ProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 4.6 SolutionstoProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 4.7 QuizonCompoundDatatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 4.8 AnswerstoQuizonCompoundDatatypes . . . . . . . . . . . . . . . . . . . . . . . . . . 121 5 CommonComputationPatterns 123 5.1 ThemapFunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 5.2 Thefilterfunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 5.3 Thefoldfunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 5.4 ThezipFunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 5.5 ProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 5.6 SolutionstoProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 5.7 QuizonCommonComputationPatterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 5.8 AnswerstoQuizonCommonComputationPatterns . . . . . . . . . . . . . . . . . . . . . 156 6 DataflowProgrammingwithFunctions 159 6.1 List-basedDataflowProgramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 6.2 Stream-basedDataflowProgramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 6.3 ProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 6.4 SolutionstoProgrammingChallenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 6.5 QuizonDataflowProgrammingwithFunctions . . . . . . . . . . . . . . . . . . . . . . . . 182 6.6 AnswerstoQuizonDataflowProgrammingwithFunctions . . . . . . . . . . . . . . . . . 185 7 ApplyingFunctionalProgramminginPractice 187 7.1 HandleCollectionsinDataProcessingApplications . . . . . . . . . . . . . . . . . . . . . 187 7.2 HandleJSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 8 Conclusion 201 8.1 WrapUp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 8.2 WheretoGofromHere? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 TheArtofFunctionalProgramming 2 1 INTRODUCTION 1 Introduction 1.1 AboutThisBook 1.1.1 Bookdescription WelcometoTheArtofFunctionalProgrammingbook! Functionalprogrammingisapowerfulandelegantprogrammingparadigm.Initiallyonlypopularamong universityresearchers,it’sgainedmuchtractioninthesoftwareindustryinthelastfewyears. Frombig companies to start-ups, engineers and managers have realized that functional programming excels at abstractionandcomposition.Functionalprogrammingallowsforhighlyconcisesolutionswithincreased safety.Thishasledtorisingdemandforsoftwareengineerswithfunctionalprogrammingskills.Thisbook willhelpyoumoveyourprogrammingskillstothenextlevel. Thisbookisgroundedonmybeliefsaboutsoftwaredevelopmentresultingfrommyreflectionaftermany yearsofstudyingandworkinginthesoftwareindustry. First,therearetonsofprogramminglanguages, frameworks,andtoolsoutthere–withmanymorecominginthefuture. Theonlywaytostayaheadof thegameinthisvastandquicklychangingsoftwareindustryistomasterthefundamentalsandprinciples thatcutacrossprogramminglanguages,frameworks,andtools. Inthecaseoffunctionalprogramming, learningtoadoptthefunctionalwayofsolvingproblemsismuchmoreproductivethanmemorizinghow towritefunctionalcodeinaparticularlanguage.Thisbookteachesthisfunctionalwayofthinking.We’ll also learn many fundamental techniques from programming languages, such as parsing, compilation, andtypechecking. Second,Ibelievethatatechniqueortoolisnotveryusefulifitdoesnothelpussolvereal-worldprob- lemsandmakeourliveseasier. Inthisbook,we’llonlylookatexamplesandexercisesthataretypically encounteredinaprogrammer’sday-to-dayjob. Furthermore,anentirechapterisdedicatedtoapplying whatwe’velearnedtoreal-worldscenarios. Inparticular,we’llusefunctionalprogrammingtoprocess collectionsofdataforane-commerceapplicationandhandletheJSONdatatype. Iliketothinkofthedualityofstrivingtograspthefundamentalprinciplesofthefunctionalparadigmwhile applyingittoreal-worldproblemspragmaticallyastheyinandyangofthejourneytomasterfunctional programming. TheArtofFunctionalProgramming 3 1 INTRODUCTION Figure1:Yinandyangasasymbolofduality Hereisthesummaryofthechaptersinthisbook: • In Chapter 1: Introduction, we’ll start the book with an introduction to functional programming. In particular, we’ll see how it can overcome some of the inherent weaknesses of the imperative programmingparadigm. We’llalsodiscusswhyfunctionalprogrammingmatterstoanysoftware engineer. • InChapter2: Expressions–TheBuildingBlocksofFunctionalPrograms,weexamineexpressions andhowtobuildcomplexexpressionsfromsimplerones. Threeaspectsofexpressions–syntax, types,andsemantics—willbecovered. Alongtheway,we’llgainamuchdeeperunderstandingof howprogramminglanguageswork,includingparsing,typechecking,interpretation,andcompila- tion. • InChapter3: BuildingAbstractionswithFunctions,we’llgettoknowlambdacalculus–amathe- maticalmodelservingasthefoundationofallfunctionalprogramminglanguages.We’lllearnhow tocapturecomputationpatternsasfunctions.Finally,we’lldiscussvarioustechniquesforworking withfunctionssuchascurrying,recursion,andhigher-orderfunctions. • InChapter4: ComplexDataTypes,we’llfocusonthecomplexdatatypestypicallyfoundinfunc- tionalprogramminglanguages,suchastuplesandlists.Furthermore,we’llusealgebraicdatatypes torepresenthierarchicaldata,andpatternmatchingtoextractdatafromcomplexdatatypes. • InChapter5: CommonComputationPatterns,we’lldiveintosomeofthemostcommoncomputa- tionpatterns,suchasmap,filter,fold,andzip.Thesefunctionscapturehighlygeneralcomputation patternsonlistsandotherdatastructuresthatcanbereusedtoformulatemanyotherfunctions. TheArtofFunctionalProgramming 4 1 INTRODUCTION • InChapter6: DataflowProgrammingwithFunctions,we’llgooverdataflowprogramming,apro- grammingparadigmthatemphasizescomposingprogramsfromexistingcomponents. We’lllearn howfunctionalprogrammingallowsustododataflowprogrammingelegantlyandreapallitsben- efits. • InChapter7:ApplyingFunctionalProgrammingtoVariousDomains,we’llapplywhatwe’velearned toprocesscollectionsofdatacommonlyfoundinmobileandwebapplications,aswellasbackend services.Furthermore,we’llusefunctionalprogrammingtorepresentandhandleJSON. We’llmainlyuseOCamlandoccasionallyHaskeltodemonstratethekeyconceptsandtechniquesoffunc- tionalprogrammingthroughoutthebook.Tocontrastfunctionalprogrammingconceptswithimperative ones,we’lluseJava.Yet,itisessentialtorepeatthatmostfunctionalprogrammingtechniquesintroduced inthisbookareuniversal.Thatmeanswecanapplythemtoalmostanyprogramminglanguagethatsup- portsthefunctionalprogrammingstyle. ThisincludesbutisnotlimitedtoSwift,Kotlin,JavaScript,Go, Python,andevenJava(usingtheJavaStreamAPI). 1.1.2 Intendedaudience Thisisabeginnerandintermediatebookaimedatsoftwareengineers, engineeringmanagers, orcom- putersciencestudentsinterestedinunderstandingtheessenceoffunctionalprogramming. Itisalsoan excellentfitforindividualswhoarecurrentlypreparingforcodinginterviewsandwanttoimprovetheir problem-solvingskills. 1.2 ABiteofFunctionalProgramming Functionalprogrammingisaprogrammingparadigm—astyleorawayofthinkingwhenwritingsoft- wareprograms. Therearemanyprogrammingparadigmsavailable,someofwhicharepresentedinthe followingdiagram. TheArtofFunctionalProgramming 5 1 INTRODUCTION Figure2:Programmingparadigms Theimperativeprogrammingparadigmistheoldest,andstillthemostpopular,paradigmusedtoday. Astheterm“imperative”indicates, thisparadigmmodelsaprogramasasequenceofcommandsthat changeaprogram’sstate–“firstdothis,thendothat.”Evenifwefollowtheobject-orientedprogramming paradigmbyencapsulatinglogicintoclasses,we’lllikelyimplementtheclassmethodsintheimperative style. Why has imperative programming dominated the programming world? In his Turing Award lecture ti- tled CanProgrammingBeLiberatedfromthevonNeumannStyle? AFunctionalStyleandItsAlgebraof Programs,thecomputerscientistJohnBackusgivesaninsightfulanswer. Accordingtohisobservation, thereasoncanbetracedbacktotheVonNeumannarchitecture.NamedafterthemathematicianJohn vonNeumann,whotookinspirationfromtheTuringmachine,itisacomputerarchitectureusedbymost computersproducedtoday. Inthefollowing,we’llreviewthevonNeumannarchitectureanddiscussseveralproblemsoftheimpera- tiveprogrammingparadigmduetoitstightcouplingwiththisarchitecture. Thenwe’llseehowthefunc- tionalprogrammingparadigmcanelegantlyovercomethoseproblems. 1.2.1 VonNeumannarchitecture In its simplest form, a Von Neumann computer consists of a Central Processing Unit (CPU), a memory, andabusthatconnectsthem. TheCPUactsasthebrainofthecomputerwiththeabilitytoexecutea predefinedsetofmachinecodeinstructions. Theseinstructionsareinbinaryform,consistingof0sand 1s,anddoaveryprimitivething,suchasaddingtwonumbersortestingwhetheranumberequalszero TheArtofFunctionalProgramming 6 1 INTRODUCTION ornot.TheCPUhasahandfulofregisterstostoredataneededwhenexecutinganinstruction. Thememoryistheplacewhereaprogramanditsdataarestored. Aprogramisasequenceofmachine codeinstructions. TheCPUandthememoryareconnectedviaabus. Duetothis,asubsetofmachine codeinstructionsisdedicatedtoloadingdatafrommemoryontotheregistersorstoringthedatafrom theregisterontothememory. ThefollowingdiagramillustratestheVonNeumannarchitecture. Figure3:ThevonNeumannarchitecture So,howdoesaprogramrun? It’squitesimple. TheCPUrunstheprogramfollowingamechanicalfetch- executecycle. First, itfetchesthefirstinstructionintheprogramandexecutesit. Thenitfetchesthe nextinstructionandexecutesit,andthiscyclecontinueson.Someinstructionsaffecttheorderofexecu- tion. Forinstance,ajumpinstructiondirectstheCPUtojumpbacktoapreviouspointoftheinstruction sequence. A branch instruction tells the CPU to branch to a particular instruction if some condition is TheArtofFunctionalProgramming 7

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.