Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Tài liệu Seven Languages in Seven Weeks pptx
Nội dung xem thử
Mô tả chi tiết
What Readers Are Saying About
Seven Languages in Seven Weeks
Knowingmultipleparadigmsgreatlyinfluencesourdesignabilities,so
I’malwaysonthelookoutforgoodbooksthat’llhelpmelearnthem.
Thisbooknicelybringsprominentparadigmstogether.Brucehas
experiencelearningandusingmultiplelanguages.Nowyoucangain
fromhisexperiencethroughthisbook.Ihighlyrecommendit.
Dr. Venkat Subramaniam
Award-winningauthorandfounder,AgileDeveloper,Inc.
Asaprogrammer,theimportanceofbeingexposedtonewprogramminglanguages,paradigms,andtechniquescannotbeoverstated.
Thisbookdoesamarvelousjobofintroducingsevenimportantand
diverselanguagesinaconcise—butnontrivial—manner,revealing
theirstrengthsandreasonsforbeing.Thisbookisakintoadim-sum
buffetforanyprogrammerwhoisinterestedinexploringnewhorizons
orevaluatingemerginglanguagesbeforecommittingtostudyingone
inparticular.
Antonio Cangiano
Softwareengineerandtechnicalevangelist,IBM
Fastenyourseatbelts,becauseyouareinforafast-pacedjourney.
Thisbookispackedwithprogramming-language-learningaction.
Bruceputsitallontheline,andtheresultisanengaging,rewardingbookthatpassionateprogrammerswillthoroughlyenjoy.Ifyou
lovelearningnewlanguages,ifyouwanttochallengeyourmind,if
youwanttotakeyourprogrammingskillstothenextlevel—thisbook
isforyou.Youwillnotbedisappointed.
Frederic Daoud
Author, Stripes...andJavaWebDevelopmentIsFunAgain and
GettingStartedwithApacheClick
Doyouwantsevenkickstartsintolearningyour“languageofthe
year”?Doyouwantyourthinkingchallengedaboutprogrammingin
general?Looknofurtherthanthisbook.Ipersonallywastakenback
intimetomyundergraduatecomputersciencedays,coastingthrough
myprogramminglanguagessurveycourse.Thedifferenceisthat
Brucewon’tletyoucoastthroughthiscourse!Thisisn’taleisurely
read—you’llhavetoworkthisbook.Ibelieveyou’llfinditbothmindblowingandintenselypracticalatthesametime.
Matt Stine
Groupleader,ResearchApplicationDevelopmentatSt.Jude
Children’sResearchHospital
IspentmostofmytimeasacomputersciencesstudentsayingIdidn’t
wanttobeasoftwaredeveloperandthenbecameoneanyway. Seven
LanguagesinSevenWeeks expandedmywayofthinkingaboutproblemsandremindedmewhatIloveaboutprogramming.
Travis Kaspar
Softwareengineer,NorthropGrumman
Ihavebeenprogrammingfor25yearsinavarietyofhardwareand
softwarelanguages.Afterreading SevenLanguagesinSevenWeeks ,I
amstartingtounderstandhowtoevaluatelanguagesfortheirobjectivestrengthsandweaknesses.Moreimportantly,IfeelasifIcould
pickoneofthemtoactuallygetsomeworkdone.
Chris Kappler
Seniorscientist,RaytheonBBNTechnologies
SevenLanguagesinSevenW eeks
APragmaticGuidetoLearning
ProgrammingLanguages
BruceA.Tate
The Pragmatic Bookshelf
Raleigh,NorthCarolina Dallas,Texas
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Wherethosedesignationsappearinthisbook,andThe
Pragmatic Programmers, LLCwas aware of a trademark claim,thedesignationshave
beenprintedininitial capitallettersor inall capitals.ThePragmaticStarterKit,The
PragmaticProgrammer,PragmaticProgramming,PragmaticBookshelfandthelinking g
devicearetrademarksofThePragmaticProgrammers,LLC.
Every precaution was taken in the preparation of this book. However, the publisher
assumesnoresponsibilityforerrorsoromissions,orfordamagesthatmayresultfrom
theuseofinformation(includingprogramlistings)containedherein.
Our Pragmatic courses, workshops, and other products can help youand your team
createbettersoftwareandhavemorefun.Formoreinformation,aswellasthelatest
Pragmatictitles,pleasevisitusat http://www.pragprog.com.
Theteamthatproducedthisbookincludes:
Editor: JackieCarter
Indexing: PotomacIndexing,LLC
Copyedit: KimWmi pset
Layout: StevePeter
Production: JanetFurlow
Customersupport: EllieCallahan
International: JulietBenda
Copyright © 2010PragmaticProgrammers,LLC.
Allrightsreserved.
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmitted,inanyform,orbyanymeans,electronic,mechanical,photocopying,recording,or
otherwise,withoutthepriorconsentofthepublisher.
PrintedintheUnitedStatesofAmerica.
ISBN-10:1-934356-59-X
ISBN-13:978-1-934356-59-3
Printedonacid-freepaper.
P1.0printing,October2010
Versoin:2010-10-28
Contents
Dedication 9
Acknowledgments 11
Foreword 14
1 Introduction 17
1.1 MethodtotheMadness . . . . . . . . . . . . . . . . . . 17
1.2 TheLanguages . . . . . . . . . . . . . . . . . . . . . . . 19
1.3 BuyThisBook. . . . . . . . . . . . . . . . . . . . . . . . 21
1.4 Don’tBuyThisBook . . . . . . . . . . . . . . . . . . . . 22
1.5 AFinalCharge. . . . . . . . . . . . . . . . . . . . . . . . 24
2 Ruby 25
2.1 QuickHistory . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2 Day1:FindingaNanny . . . . . . . . . . . . . . . . . . 28
2.3 Day2:FloatingDownfromtheSky . . . . . . . . . . . 35
2.4 Day3:SeriousChange. . . . . . . . . . . . . . . . . . . 48
2.5 WrappnigUpRuby . . . . . . . . . . . . . . . . . . . . . 56
3 Io 60
3.1 IntroducingIo . . . . . . . . . . . . . . . . . . . . . . . . 60
3.2 Day1:SkippingSchool,HangingOut . . . . . . . . . . 61
3.3 Day2:TheSausageKing . . . . . . . . . . . . . . . . . 74
3.4 Day3:TheParadeandOtherStrangePlaces . . . . . . 83
3.5 WrappnigUpIo . . . . . . . . . . . . . . . . . . . . . . . 92
4 Prolog 95
4.1 AboutProlog . . . . . . . . . . . . . . . . . . . . . . . . . 96
4.2 Day1:AnExcellentDriver. . . . . . . . . . . . . . . . . 97
4.3 Day2:FifteenMinutestoWapner . . . . . . . . . . . . 109
4.4 Day3:BlowingUpVegas . . . . . . . . . . . . . . . . . . 120
4.5 WrappnigUpProlog. . . . . . . . . . . . . . . . . . . . . 132
CONTENTS 8
5 Scala 135
5.1 AboutScala . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.2 Day1:TheCastleontheHill . . . . . . . . . . . . . . . 139
5.3 Day2:ClippingBushesandOtherNewTricks . . . . . 153
5.4 Day3:CuttingThroughtheFluff. . . . . . . . . . . . . 167
5.5 WrappnigUpScala . . . . . . . . . . . . . . . . . . . . . 176
6 Erlang 181
6.1 IntroducingErlang . . . . . . . . . . . . . . . . . . . . . 181
6.2 Day1:AppearingHuman . . . . . . . . . . . . . . . . . 185
6.3 Day2:ChangingForms . . . . . . . . . . . . . . . . . . 195
6.4 Day3:TheRedPill . . . . . . . . . . . . . . . . . . . . . 207
6.5 WrappnigUpErlang . . . . . . . . . . . . . . . . . . . . 219
7 Clojure 223
7.1 IntroducingClojure. . . . . . . . . . . . . . . . . . . . . 224
7.2 Day1:Training Luke . . . . . . . . . . . . . . . . . . . . 225
7.3 Day2:YodaandtheForce. . . . . . . . . . . . . . . . . 243
7.4 Day3:AnEyeforEvil . . . . . . . . . . . . . . . . . . . 256
7.5 WrappnigUpClojure . . . . . . . . . . . . . . . . . . . . 264
8 Haskell 268
8.1 IntroducingHaskell. . . . . . . . . . . . . . . . . . . . . 268
8.2 Day1:Logical . . . . . . . . . . . . . . . . . . . . . . . . 269
8.3 Day2:Spock’sGreatStrength . . . . . . . . . . . . . . 285
8.4 Day3:TheMindMeld . . . . . . . . . . . . . . . . . . . 294
8.5 WrappnigUpHaskell. . . . . . . . . . . . . . . . . . . . 309
9 Wrap-Up 313
9.1 ProgrammingModels . . . . . . . . . . . . . . . . . . . . 313
9.2 Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . 317
9.3 ProgrammingConstructs . . . . . . . . . . . . . . . . . 319
9.4 FindingYourVocie . . . . . . . . . . . . . . . . . . . . . 321
A Bibliography 322
Index 323
Reporterratum
thiscopyis (P1.0printing,October2010)
Dedication
ThefivemonthsfromDecember2009throughApril2010wereamong
themostdifficultofmylife.Mybrother,notyet47yearsold,hademergencybypasssurgery.Noonehadanycluethatanythingwaswrong
atall.(He came throughthe surgerywithoutfurther incidentandis
doingwell.)InlateMarch,mysisterwasdiagnosedwithbreastcancer.
ThebiggestshockofallcameinearlyMarch.Mymotherwasdiagnosed
withterminalcancer.Afewshortweekslater,shewasgone.
As youwouldexpect,Iamleftto strugglewiththe grief ofajarring
and unexpected loss because of a brutally efficient disease. I would
notbehumanotherwise.Butstrangely,thisexperiencehasnotbeen
anentirelynegative one.You see,mymotherwas atpeacewiththe
remarkablelifeshelived,herrelationshipswithherfamilywerestrong
andfulfilling,andshewas exactlywhere shewantedtobewithher
faith.
Lynda Lyle Tateputhercreativeenergyintopaintingwithwatercolors.
ShesharedherartprimarilythroughherMadisonAvenueArtGallery
andherclasses.BeforeIlefthome,Ihadtheopportunitytotakeafew
lessonsfromher.Forsomeonefromatechnicalprofession,theexperiencewasalwaysalittledisorienting.Iwouldvisualizethemasterpiece
onmyblankcanvas.Astheactualimagetookshape,itdriftedfurther
andfurtherfrommyoriginalvision.WhenIdespairedthatthingswere
beyondmyability tofix,Momlookedovermy shoulderandtoldme
whatshesaw.Afterafewflicksofhertalentedwristaddeddarksto
accentuatedepthandhighlightstoaddclarityanddetail,IwouldrealizethatIhadnotbeentoofarastrayatall.Itjusttookagiftedtouchto
bringbackmycreationfromthebrinkofdisaster.Then,Iwouldthrow
myexcitedarmsupinvictoryandtelleveryoneintheclassaboutthis
thingIhadcreated,notyetrealizingthateachmemberoftheclasswas
goingthroughtheirownprivateburstofjoy.
DEDICATION 10
Afteralittlewhile,IlearnedthatMomwasworkingonanothercanvas
as well. Throughher churchand throughher profession, she’d find
brokenpeople.Encounteringalostspousehereoratroubledmarriage
there,mymotherwouldbringthemintoclasswhereshewouldusethe
paintandpapertoslightlyopenadoorthathadbeenslammedshut.
Aswespentour lastweektogether,personafterpersonwouldcome
throughherroomdevastatedatthethoughtoflosingtheirteacher,but
Mom would tellthe perfectjoke or offer the right word of kindness,
comforting thosewhocame tocomforther.Igottomeetthehuman
canvaseswhohadbeenputrightbythemasterandgoneontodogreat
things.Itwasahumblingexperience.
When Itold my mother thatI would dedicate this book to her, she
said that she would like that, but shehadnothing to do withcomputers.Thatistrueenough.TheverythoughtofWnidowswouldleave
herhelpless.ButMom,youhavehadeverythingtodowith me.Your
well-timedwordsofencouragementinspiredme,yourloveofcreativity
shapedme,andyourenthusiasmandloveoflifeguidemeevennow.
AsIthinkabouttheseexperiences,Ican’thelpbutfeelalittlebetter
andalittlestrongerbecauseI,too,amacanvasshapedbythemaster.
ThisbookisdedicatedwithlovetoLynda Lyle Tate,1936–2010.
Reporterratum
thiscopyis (P1.0printing,October2010)
Acknowledgments
ThisisthemostdemandingbookIhaveeverwritten.It’salsothemost
rewarding.Thepeoplewhohaveofferedtohelpinvariouswayshave
madeitso.Thanksfirstandforemosttomyfamily.KaylaandJulia,
yourwritingamazesme.You can’tyetimaginewhatyoucanaccomplish.Maggie,youaremyjoyandinspiration.
Inthe Ruby community,thanks to Dave Thomas for turning me on
to the language thatturned my career upside down and helped me
havefunagain.ThanksalsotoMatzforyourfriendshipandyouroffer
toshareyour thoughtswithmyreaders.You invitedmetoJapanto
visittheplacewhereRubywasborn,andthatexperienceinspiredme
muchmorethanyouwilleverknow.ToCharlesNutter,EvanPhoenix,
andTim Bray,thanksfortheconversationsabouttopicsinthisbook
thatmusthaveseemedtiresomebuthelpedmerefineandshapethe
message.
IntheIocommunity,thankstoJeremyTregunna forhelpingmeget
pluggedinandsharingsomecoolexamplesforthebook.Yourreviews
were among the best. They were timely and helped build a much
stronger chapter. Steve Dekorte, you’ve created something special,
whetherornotthemarketplaceeverrecognizesitasso.Theconcurrencyfeaturesrock,andthelanguagehasintrinsicbeauty.Icandefinitely appreciatehowmuchofthis language feels right. Thanks for
helping this neophyte debug his installation. Thanks also for your
thoughtfulreviewsandyourinterviewthathelpedmecapturetheessenceofIo.Youcapturedtheimaginationofthebetareadersandcreatedthefavoritelanguageofmanyofthem.
In the Prolog community, thanks to Brian Tarbox for sharing your
remarkableexperiencewithmyreaders.Thedolphinprojects,featured
onNova,certainlyaddadramaticflairtothePrologchapter.Special
thanks go to Joe Armstrong. You can see how much your feedback
shapedthechapterandtheoverallbook.Thanksalsoforcontributing
ACKNOWLEDGMENTS 12
yourmap-coloringexampleandyourideasforAppend.Theywerethe
rightexamplesdeliveredattherighttime.
IntheScalacommunity,thankstomygoodfriendVenkat Subramaniam.Your Scalabookisbothrichandunderstandable.Ileanedon
itheavily.I greatly appreciate your review and the little bits ofhelp
that you offered along the way. Those little bits of your time saved
me tremendous anguish and let me focus on the task of teaching.
ThanksalsotoMartinOderskyforhelpingthisstrangerbysharingyour
thoughtswithmyreaders.Scalatakesauniqueandbraveapproach
tointegratingfunctionalprogrammingparadigmswithobject-oriented
paradigms.Youreffortsaregreatlyappreciated.
IntheErlangcommunity,IagainthankJoeArmstrong.Yourkindness
andenergyhavehelpedmeformtheideasinthisbook.Your tireless
promotionofthewaydistributed,fault-tolerantsystemsshouldbebuilt
is working. More than any other idea in any other language in this
book,Erlang’s“Letitcrash”philosophymakessensetome.Ihopeto
seethoseideasmorebroadlyadopted.
IntheClojurecommunity,thankstoStuartHallowayforyourreviews
and ideas that forced me to work harder to bring a better book to
myreaders.Your insights intoClojureandyour instinctshelpedme
understandwhatwasimportant.Yourbookwasalsohugelyinfluential
intheClojurechapterandactuallychangedthewayIattackedsome
problemsinotherchaptersaswell.Yourapproachinyourconsulting
practiceisgreatlyappreciated.Your’ebringingmuch-neededsimplicity
andproductivitytothisindustry.ThanksalsotoRichHickeyforyour
thoughtfulideasonthecreationofthelanguageandwhatitmeansto
beaLispdialect.SomeideasinClojureareintenselyradicalandyet
sopractical.Congratulations.Youv’efoundawaytomakeLisprevolutionary.Again.
Inthe Haskell community,thanks toPhillipWadelr for the opportunitytolookinsidetheprocessthatcreatedHaskell.We shareapassion for teaching, and you’re very good atit. Thanks also to Simon
Peyton-Jones.Ienjoyedworkingthroughyour interview,theinsights
youadded,andtheuniqueperspectiveyoubroughttothesereaders.
Thereviewersdidanoutstandingjobwiththisbook.ThankstoVladimirG.Ivanovic,CraigRiecke,PaulButcher,FredDaoud,AaronBedra,
DavidEisinger,AntonioCangiano,andBrianTarbox.You formedthe
most effective review team I’ve ever worked with. The book is much
Reporterratum
thiscopyis (P1.0printing,October2010)
ACKNOWLEDGMENTS 13
stronger for it.Iknowthat reviewingabookatthis levelofdetailis
thankless,demandingwork.Thoseofuswhostillliketechnicalbooks
thankyou.Thepublishingbusinesscouldnotexistwithoutyou.
Ialsowanttothankthoseofyouwhosharedyourideasaboutlanguage
choiceandprogrammingphilosophy.Atvarioustimes,NealFord,John
Heintz,MikePerham,andIanWarshakmadesignificantcontributions.
ThesekindsofconversationsmademelooksmarterthanIreallyam.
Betareaders,thankyouforreadingthebookandkeepingmeworking.
Yourcommentshaveshownmethatagoodnumberofyouareworking
throughthelanguagesratherthancasuallyskimming.I’vechangedthe
bookbasedonhundredsofcommentssofarandexpecttodoevenmore
throughoutthelifeofthebook.
Finally,to the teamatthePragmaticBookshelf,I offermy sincerest
gratitude.DaveThomasandAndyHunt,youhavehadanincalculable
impactonmycareerasaprogrammerandagainasanauthor.This
publishingplatformhasmadewritingviableagainforme.We cantake
abooklikethisonethatmightnotbeasattractivetothemassmarket
andmakeitfinanciallyworthwhile.Thankstoallthemembersofthe
publishingteam.JackieCarter,yourgentlehandandguidancewere
whatthisbookneeded,andIhopeyouenjoyedourconversationsas
muchasIdid.Thankstothosewholaboredinmyshadowtomake
thisbookthebestitcouldbe.Specifically,Iwanttothanktheteam
thatlaboredsohardtomakethisbooklookgoodandcorrectallofmy
badhabits,includingKimWmi pset,thecopyeditor;SethMaislin,the
indexer;StevePeter,the typesetter;andJanetFurlow,theproducer.
Thisbookwouldnotbewhatitiswithoutyou.
Asalways,mistakesthatslippedthroughthisfineteamareallmine.
ForthoseofyouImissed,Ioffermysincerestapologies.Anyoversight
wasnotintentional.
Finally,thankstoallofmyreaders.Ithinkthatrealhard-copybooks
havevalue,andIcanfollowmypassionandwritebecauseyoudo,too.
BruceTate
Reporterratum
thiscopyis (P1.0printing,October2010)
Foreword
From the yet to be written “How Proust Can Make You a Better
Programmer”
byJoeArmstrong ,CreatorofErlang
“TheGmaileditorcannotgettypographicquotesright.”
“Disgraceful,”saidMargery,“thesignofanilliterateprogrammeranda
decadentculture.”
“Whatshouldwedoaboutit?”
“Wemustinsistthatthenextprogrammerwehirehasreadallof‘Ala
recherchedutempsperdu.”’
“Allsevenvolumes?”
“Allsevenvolumes.”
“Willitmakethembetteratpunctuationandmakethemgettheirquotes
right?”
“Notnecessarily,butitwillmakethemabetterprogrammer.It’saZen
thing....”
Learningtoprogramislikelearningtoswim.Noamountoftheoryis
asubstitutefordivingintothepoolandflailingaroundinthewater
gaspingforair.Thefirsttimeyousinkunderthewater,youpanic,but
whenyoubobtothesurfaceandgulpinsomeair,youfeelelated.You
thinktoyourself,“Icanswim.”Atleastthat’showIfeltwhenIlearned
toswim.
It’sthesamewithprogramming.Thefirststepsarethemostdifficult,
andyouneedagoodteachertoencourageyoutojumpintothewater.
BruceTateissuchateacher.Thisbookgivesyoutheopportunityto
startwithwhatisthemostdifficultpartoflearningtoprogram,namely,
gettingstarted.
FOREWORD 15
Let’sassumethatyou’veactuallymanagedthedifficulttaskofdownloadingandinstallingtheinterpreterorcompilerforthelanguageyou
are interested in. What should youdonext?What will be your first
program?
Bruce neatly answers this question. Justtype in the programs and
programfragmentsinthisbooktoseewhetheryoucanreproducehis
results.Don’tthinkaboutwritingyourownprogramsyet—justtryto
reproducetheexamplesinthebook.Asyougrowinconfidence,you
willbeabletotackleyourownprogrammingprojects.
Thefirststepinacquiringanynewskillisnotbeingabletodoyourown
thingbutbeingabletoreproducewhatotherpeoplehavedonebefore
you.Thisisthequickestwaytomasteringaskill.
Gettingstartedwithprogramminginanewlanguageisnotsomuch
adeepexerciseinunderstandingtheunderlyingprinciplesthatalanguage embodies; itis rather a matter of getting the semicolons and
commas inthe rightplacesandunderstanding theweirderrormessagesthatthesystemspitsoutwhenyoumakeanerror.Itisnotuntil
yougetbeyondthemessybusinessofenteringaprogramandgettingit
throughthecompilerthatyoucanevenstarttothinkaboutthemeaningofthedifferentlanguageconstructs.
Onceyou’vegottenthroughthemechanicsofenteringandrunningprograms,youcansitbackandrelax.Your subconsciousdoestherest.
Whileyourconsciousbrainisfiguringoutwheretoputthesemicolons,
yoursubconsciousisfiguringoutthedeepmeaningthatliesunderneaththesurfacestructures.Thenyou’llwakeuponedaysuddenly
understandingthedeepermeaningofalogicprogramorwhyaparticularlanguagehadaparticularconstruct.
Knowingasmallamountaboutmanylanguagesisausefulskill.Ioften
findthatIneedtounderstandabitofPythonorRubytosolveaparticularproblem.TheprogramsIdownloadfromtheInternetareoften
writteninavarietyoflanguagesandneedalittletweakingbeforeIcan
usethem.
Eachlanguagehasitsownsetofidioms,itsstrengths,anditsweaknesses.Bylearningseveraldifferentprogramminglanguages,youwill
beabletoseewhichlanguageisbestsuitedtothekindsofproblems
thatinterestyoumost.
Reporterratum
thiscopyis (P1.0printing,October2010)