Table Of ContentUndergraduate Topics in Computer Science
UndergraduateTopicsinComputerScience(UTiCS)delivershigh-qualityinstruc-
tionalcontentforundergraduatesstudyinginallareasofcomputingandinformation
science.Fromcorefoundationalandtheoreticalmaterialtofinal-yeartopicsandap-
plications, UTiCS books take fresh, concise, and modern approach and are ideal
for self-study or for a one- or two-semester course. The texts are all authored by
establishedexpertsintheirfields,reviewedbyaninternationaladvisoryboard,and
containnumerousexamplesandproblems.Manyincludefullyworkedsolutions.
Forfurthervolumes:
http://www.springer.com/series/7592
Maurizio Gabbrielli and Simone Martini
Programming
Languages:
Principles
and Paradigms
Prof.Dr.MaurizioGabbrielli Prof.Dr.SimoneMartini
UniversitàdiBologna UniversitàdiBologna
Bologna Bologna
Italy Italy
Serieseditor
IanMackie
Advisoryboard
SamsonAbramsky,UniversityofOxford,UK
ChrisHankin,ImperialCollegeLondon,UK
DexterKozen,CornellUniversity,USA
AndrewPitts,UniversityofCambridge,UK
HanneRiisNielson,TechnicalUniversityofDenmark,Denmark
StevenSkiena,StonyBrookUniversity,USA
IainStewart,UniversityofDurham,UK
DavidZhang,TheHongKongPolytechnicUniversity,HongKong
ISSN1863-7310
ISBN978-1-84882-913-8 e-ISBN978-1-84882-914-5
DOI10.1007/978-1-84882-914-5
SpringerLondonDordrechtHeidelbergNewYork
BritishLibraryCataloguinginPublicationData
AcataloguerecordforthisbookisavailablefromtheBritishLibrary
LibraryofCongressControlNumber:2010922995
TranslatedfromtheoriginalItalianedition:“Linguaggidiprogrammazione:principieparadigmi”,pub-
lishedin2006byMcGraw-HillCompanies,PublishingGroupItalia.
©Springer-VerlagLondonLimited2010
Apartfromanyfairdealingforthepurposesofresearchorprivatestudy,orcriticismorreview,asper-
mittedundertheCopyright,DesignsandPatentsAct1988,thispublicationmayonlybereproduced,
storedortransmitted,inanyformorbyanymeans,withthepriorpermissioninwritingofthepublish-
ers,orinthecaseofreprographicreproductioninaccordancewiththetermsoflicensesissuedbythe
CopyrightLicensingAgency.Enquiriesconcerningreproductionoutsidethosetermsshouldbesentto
thepublishers.
Theuseofregisterednames,trademarks,etc.,inthispublicationdoesnotimply,evenintheabsenceofa
specificstatement,thatsuchnamesareexemptfromtherelevantlawsandregulationsandthereforefree
forgeneraluse.
Thepublishermakesnorepresentation,expressorimplied,withregardtotheaccuracyoftheinformation
containedinthisbookandcannotacceptanylegalresponsibilityorliabilityforanyerrorsoromissions
thatmaybemade.
Printedonacid-freepaper
SpringerispartofSpringerScience+BusinessMedia(www.springer.com)
ToFrancescaandAntonella,
whowillneverwanttoreadthisbook
butwhocontributedtoitbeingwritten.
ToCostanza,MariaandTeresa,whowillreaditperhaps,
butwhohavedoneeverythingtostopitbeingwritten.
Foreword
Withgreatpleasure,Iacceptedtheinvitationextendedtometowritethesefewlines
of Foreword. I accepted for at least two reasons. The first is that the request came
tomefromtwocolleaguesforwhomIhavealwayshadthegreatestregard,starting
from the time when I first knew and appreciated them as students and as young
researchers.
The second reason is that the text by Gabbrielli and Martini is very near to the
bookthatIwouldhavelikedtohavewrittenbut,forvariousreasons,neverhave.In
particular,theapproachadoptedinthisbookistheonewhichImyselfhavefollowed
when organising the various courses on programming languages I have taught for
almostthirtyyearsatdifferentlevelsundervarioustitles.
Theapproach,summarisedin2words,isthatofintroducingthegeneralconcepts
(eitherusinglinguisticmechanismsortheimplementationstructurescorresponding
tothem)inamannerthatisindependentofanyspecificlanguage;oncethisisdone,
“real languages” are introduced. This is the only approach that allows one to re-
veal similarities between apparently quite different languages (and also between
paradigms).Atthesametime,itmakesthetaskoflearningdifferentlanguageseas-
ier. In my experience as a lecturer, ex-students recall the principles learned in the
courseevenaftermanyyears;theystillappreciatetheapproachwhichallowedthem
toadapttotechnologicaldevelopmentswithouttoomuchdifficulty.
The book by Gabbrielli and Martini has, as central reference point, an under-
graduate course in Computer Science. For this reason, it does not have complex
prerequisites and tackles the subject by finding a perfect balance between rigour
andsimplicity.Particularlyappreciatedandsuccessfulistheforcewithwhichthey
illuminate the connections with other important “areas of theory” (such as formal
languages,computability,semantics)whichthebookrightlyincludes(afurtherjus-
tification for their inclusion being that these topics are no longer taught in many
degreecourses).
GiorgioLevi,Pisa.
vii
Introduction
Faciliusperpartesincognitionemtotiusadducimur
(Seneca,Epist.89,1)
Learningaprogramminglanguage,formoststudentsincomputing,isakintoa
riteofpassage.Itisanimportanttransition,soonrecognisedasinsufficient.Among
thetoolsofthetrade,therearemanylanguages,soanimportantskillforthegood
computerprofessionalistoknowhowtomovefromonelanguagetoanother(and
howtolearnnewones)withnaturalnessandspeed.
This competence is not obtained by learning many different languages from
scratch. Programming languages, like natural languages, have their similarities,
analogiesandtheyinheritcharacteristicsfromeachother.Ifitisimpossibletolearn
tensoflanguageswell,itispossiblecompletelytounderstandthemechanismsthat
inspireandguidethedesignandimplementationofhundredsofdifferentlanguages.
Thisknowledgeofthe“parts”facilitatestheunderstandingofthe“whole”ofanew
languageandthereforeunderpinsafundamentalmethodologicalcompetenceinthe
life of the computing professional, at least as far as it allows them to anticipate
innovationsandtooutlivetechnologiesthatgrowobsolete.
Itisforthesereasonsthatacourseonthegeneralaspectsofprogramminglan-
guagesis,throughouttheworld,akeystepatadvancedlevelforacomputingpro-
fessional(atuniversityorinaprofession). The fundamentalcompetenceswhicha
computingprofessionalmustpossessaboutprogramminglanguagesareofatleast
fourtypes:
Someaspectsthatareproperlyconsideredlinguistic.
•
Knowledgeofhowlanguageconstructscanbeimplementedandtherelativecost
•
oftheseimplementations.
Knowledgeofthosearchitecturalaspectsinfluencingimplementation.
•
Compilationtechniques.
•
It is rare that a single course dealswith all four of these aspects. In particular,de-
scriptionofarchitecturalaspectsandcompilationtechniquesarebothtopicsthatare
sufficiently complex and elaborate to merit independent courses. The remaining 2
aspectsareprimarilythecontentofageneralcourseonprogramminglanguagesand
comprisetheprinciplesubjectofthisbook.
ix
x Introduction
Theliteratureisrichintextsdealingwiththesesubjects.Generationsofstudents
haveusedthemintheirlearning.Allthesetexts,though,haveinmindanadvanced
reader who already understands many different programming languages, who al-
ready has a more than superficial competence with fundamental mechanisms and
who is not afraid when confronted by a fragment of code written in an unknown
language(becausetheyareableunderstanditbyanalogyusingthedifferencesbe-
tween it and what they already know). These are texts, then, that we can say are
on“comparativelanguages”.Thesearelong,deepandstimulating,buttheyaretoo
longanddeep(read:difficult)forthestudentwhobeginstheircareerwithasingle
programminglanguage(oratmost2)andwhostillhastolearnthebasicconcepts
indetail.
Thistextaimstofillthisgap.Expertswillseethatthecontentinlargemeasure
reflectsclassicalthemes.Buttheseverythemesaretreatedinanelementaryfashion,
assuming only the indispensable minimum of prerequisites. The book also avoids
being a catalogue of the differences between different existing programming lan-
guages.Theideal(orreference)readerisonewhoknowsonelanguage(well)(for
example, Pascal, C, C++ or Java). It is better if they have had some exposure to
anotherlanguageorparadigm.Referencestolanguagesthatarenowobsoletehave
alsobeenavoidedandcodeexamplesarerarelywritteninaspecificprogramming
language. The text freely uses a sort of pseudo-language (whose concrete syntax
was inspired by C and Java) and seeks, in this way, to describe the most relevant
aspectsofdifferentlanguages.
Everysooften,theboxesatthetopofpagescontaindevelopmentofmaterialor
anoteonabasicconceptorsomethingspecificaboutcommonlanguages(C,C++,
Java;MLand LISP forfunctionallanguages; PROLOGforlogic-programminglan-
guages).Thematerialinboxescanalmostalwaysbeomittedonafirstreading.
Everychaptercontainsashortsequenceofexerciseswhichshouldbeunderstood
as a way of demonstrating an understanding of the material. There are no truly
difficultexercisesoranythatrequiremorethan10minutesfortheirsolution.
Chapter 3 (Foundations) deals with themes that are not usually encountered in
a book on programming languages. It is, however, natural, while discussing static
semanticsandcomparinglanguages,toaskwhatarethelimitstosyntacticanalysis
ofprogramsandwhetherwhatcanbedoneinonelanguagecanalsobedoneinan-
other.Ratherthansendthereadertoanothertext,giventheculturalandpragmatic
relevance of these questions, we decided to answer these questions directly. In an
informalbutrigorousmanner,inthespaceofafewpages,wepresenttheundecid-
abilityofthehaltingproblem.Wealsoshowthatallgeneralpurposeprogramming
languages express the same class of functions. This helps students who do not al-
wayshavecompletecoursesonfoundationsunderstandtheprincipalresultsonthe
limitationsoncomputations.
As well as principles, the text also introduces the three principal programming
paradigms:objectoriented(athemethatisalreadyobligatoryincomputing),func-
tionalandlogicprogramming.Theneedtowriteanintroductorytextisthereason
fortheexclusionofimportantthemes,suchasconcurrencyandscriptinglanguages,
whosemasteryrepresentimportantskills.
Introduction xi
Use of the text The text is first of all a university textbook, even if there is an
almosttotalabsenceofmathematicalandformalprerequisites(thislackmakesthe
book suitable for personal study by the professional who wishes to deepen their
knowledge of the mechanisms that lie behind the languages they use). The choice
of themes and the presentation style were largely influenced by the experience of
teachingthecontentaspartofthedegreecourseinComputerScienceintheFaculty
ofMathematical,PhysicalandNaturalSciencesattheUniversityofBologna.
Inourexperience,acourseonprogramminglanguagesfor6creditsinthesecond
yearofa3-yeardegreecoursecancovermostofthefundamentalaspectscovered
inthefirsttenchapters(say4/5ofthem)and,perhaps,includingabriefoutlineof
oneoftheremainingparadigms.Withincreaseinstudentmaturity,thequantityof
materialthatcanbepresentedwillclearlyincrease.Inamaster’sdegreecourse,the
materialcouldalsobecompletedbyatreatmentofcompilation.
Acknowledgements OurthankstoGiorgioLevigoesbeyondthefactthathehad
the grace to write the Foreword. Both of us owe to him our first understanding of
themechanismsthatunderpinprogramminglanguages.Histeachingappearsinthis
bookinawaythatisanythingbutmarginal.
Ugo Dal Lago drew the figures using METAPOST, Cinzia Di Giusto, Wilmer
Ricciotti, Francesco Spegni and Paolo Tacchella read and commented attentively
onthedraftsofsomechapters.Thefollowingpeoplepointedoutmisprintsander-
rors:IreneBorra,FerdinandaCamporesi,MarcoComini,MicheleFilannino,Matteo
Friscini,StefanoGardenghi,GuidoGuizzunti,GiacomoMagisano,FlavioMarchi,
FabrizioMassei,JacopoMauro,MaurizioMolle,MirkoOrlandelli,MarcoPedicini,
Andrea Rappini, Andrea Regoli, Fabiano Ridolfi, Giovanni Rosignoli, Giampiero
Travaglini, Fabrizio Giuseppe Ventola. We gladly acknowledge the support of the
DipartimentodiScienzedell’InformazioneoftheUniversitàdiBolognatowardsthe
Englishtranslation.
MaurizioGabbrielli
Bologna
SimoneMartini
Bologna