0% found this document useful (0 votes)
8 views97 pages

PPL Unit 1 To 5 Notes

Uploaded by

ancyrajesh7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views97 pages

PPL Unit 1 To 5 Notes

Uploaded by

ancyrajesh7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Principles of

Programming
Languages
CONTENTS

UNIT1.PRELIMINARYCONCEPTS
ReasonsforStudyingConceptsofProgrammingLanguages
ProgrammingDomains,LanguageEvaluationCriteria
InfluencesonLanguageDesign,LanguageCategories
ProgrammingParadigms-Imperative,FunctionalProgramminglanguage
LanguageImplementation-compilationandinterpretation
Programmingenvironments

SYNTAXANDSEMANTICS

TheGeneralProblemsofDescribingSyntaxandsemantics
BNF
EBNFforcommonprogramminglanguagefeatures
AmbiguousGrammar

UNIT2.DATATYPESANDVARIABLES
IntroductiontoPrimitiveDataTypes
User-DefinedDataTypesandArrayTypes
Record,UnionandPointerandReferencetypes
Names,Variables,TheConceptofBinding
TypeChecking,TypeCompatibility
StrongTypes,NamedConstants,variableinitialization

EXPRESSIONSANDSTATEMENTS&CONTROLSTRUCTURES

Expression:[Arithmetic,RelationalandBooleanExpressions]
Short-CircuitEvaluation
AssignmentStatements,Mixed-
ModeAssignment[ReferentialTransparency&FunctionalProgramming]
ControlStructures[statementLevelControlStructures,Compoundstat
ements]
SelectionStatements,IterativeStatements,UnconditionalBranching,Gu
ardedCommands

UNIT3.SUBPROGRAMSANDBLOCKS
FundamentalsofSubprograms
DesignIssuesforSubprograms
ParameterPassingMethods
ParametersSubprogramsasparameters
OverloadedSubprograms&Operations
GenericSubprograms,separatelycompiledmodules
Co-Routines

1
UNITIV.ABSTRACTDATATYPES
Abstract-datatypes[Abstraction&Encapsulation]
IntroductiontoDataAbstraction,DesignIssues
LanguageExamples
C++ParameterizedAbstractDataTypes
DataTypes
Object-OrientedProgramminginSmalltalk
Object-OrientedProgramminginC++
Object-OrientedProgramminginJava
Object-OrientedProgramminginC#
Object-OrientedProgramminginAda95

EXCEPTIONHANDLING&LOGICPROGRAMMING

ExceptionHandling:Exceptions,ExceptionPropagation
ExceptionHandlerinAda
C++andJava
Logic Programming Language : Introduction An Overview of Logic
Programming
TheBasicElementsofPROLOG
ApplicationsofLogicProgramming

UNIT-V.FUNCTIONALPROGRAMMINGLANGUAGES&SCRIPTINGLANGUAGE

FunctionalProgrammingLanguageIntroduction
FundamentalsofFunctionalProgrammingLanguages,LISPProgramming
FundamentalsofML,examples
FundamentalsofHaskell,functionsyntaxandexamples
Applications of Functional Programing language and Comparison
ofFunctionalandImperativeLanguages

2
UNIT-1
PreliminaryConcepts

Background
 Frankly,wedidn‘thavethevaguestideahowthething[FORTRANlanguageandcompil
er] would work out in detail. …We struck out simply to optimize the
objectprogram,therunningtime,becausemostpeopleatthattimebelievedyoucould
n‘tdothatkindofthing.Theybelievedthatmachined-
codedprogramswouldbesoinefficientthatitwouldbeimpracticalformanyapplicati
ons.
 JohnBackus,unexpectedsuccessesarecommon–
thebrowserisanotherexampleofanunexpectedsuccess

ReasonsforStudyingConceptsofProgrammingLanguages-CO1
 Increasedabilitytoexpressideas
 Improvedbackgroundforchoosingappropriatelanguages
 Increasedabilitytolearnnewlanguages
 Betterunderstandingofsignificanceofimplementation
 Overalladvancementofcomputing

ProgrammingDomains–CO1
 Scientificapplications
– Largenumberoffloatingpointcomputations
– Fortran
 Businessapplications
– Producereports,usedecimalnumbersandcharacters
– COBOL
 Artificialintelligence
– Symbolsratherthannumbersmanipulated
– LISP
 Systemsprogramming
– Needefficiencybecauseofcontinuoususe
– C
 WebSoftware
– Eclecticcollectionoflanguages:markup(e.g.,XHTML),scripting(e.g.,PHP),gener
al-purpose(e.g.,Java)

3
LanguageEvaluationCriteria–CO1,CO2

 Readability:theeasewithwhichprogramscanbereadandunderstood
 Writability :theeasewithwhichalanguagecanbeusedtocreateprograms
 Reliability :conformancetospecifications(i.e.,performstoitsspecifications)
 Cost :theultimatetotalcost

Readability
 Overallsimplicity
– Amanageablesetoffeaturesandconstructs
– Fewfeaturemultiplicity(meansofdoingthesameoperation)
– Minimaloperatoroverloading
 Orthogonality
– Arelativelysmallsetofprimitiveconstructscanbecombinedinarelativelysmallnumb
erofways
– Everypossiblecombinationislegal
 Controlstatements
– Thepresenceofwell-knowncontrolstructures(e.g.,whilestatement)
 Datatypesandstructures
– Thepresenceofadequatefacilitiesfordefiningdatastructures
 Syntaxconsiderations
– Identifierforms:flexiblecomposition
– Specialwordsandmethodsofformingcompoundstatements
– Formandmeaning:self-descriptiveconstructs,meaningfulkeywords
Writability
 SimplicityandOrthogonality
– Fewconstructs,asmallnumberofprimitives,asmallsetofrulesforcombiningthem
 Supportforabstraction
– Theabilitytodefineandusecomplexstructuresoroperationsinwaysthatallowdetails
tobeignored
 Expressivity
– Asetofrelativelyconvenientwaysofspecifyingoperations
– Example:theinclusionofforstatementinmanymodernlanguages
Reliability
 Typechecking
– Testingfortypeerrors
 Exceptionhandling
– Interceptrun-timeerrorsandtakecorrectivemeasures
 Aliasing
– Presenceoftwoormoredistinctreferencingmethodsforthesamememorylocation
 Readabilityandwritability
– Alanguagethatdoesnotsupport“natural”waysofexpressinganalgorithmwillnecess
arilyuse“unnatural”approaches,andhencereducedreliability
Cost
 Trainingprogrammerstouselanguage
 Writingprograms(closenesstoparticularapplications)
 Compilingprograms
 Executingprograms

4
 Languageimplementationsystem:availabilityoffreecompilers
 Reliability:poorreliabilityleadstohighcosts
 Maintainingprograms
Others
 Portability
– Theeasewithwhichprogramscanbemovedfromoneimplementationtoanother
 Generality
– Theapplicabilitytoawiderangeofapplications
 Well-definedness
– Thecompletenessandprecisionofthelanguage‘sofficialdefinition

5
InfluencesonLanguageDesign-CO3
 ComputerArchitecture
– Languagesaredevelopedaroundtheprevalentcomputerarchitecture,knownast
hevonNeumannarchitecture
 ProgrammingMethodologies
– Newsoftwaredevelopmentmethodologies(e.g.,object-
orientedsoftwaredevelopment)ledtonewprogrammingparadigmsandbyextensio
n,newprogramminglanguages

ComputerArchitecture
 Well-knowncomputerarchitecture:VonNeumann
 Imperativelanguages,mostdominant,becauseofvonNeumanncomputers
– Dataandprogramsstoredinmemory
– MemoryisseparatefromCPU
– InstructionsanddataarepipedfrommemorytoCPU
– Basisforimperativelanguages
 Variablesmodelmemorycells
 Assignmentstatementsmodelpiping
 Iterationisefficient

Figure1.1ThevonNeumannComputerArchitecture

ProgrammingMethodologies
 1950sandearly1960s:Simpleapplications;worryaboutmachineefficiency
 Late1960s:Peopleefficiencybecameimportant;readability,bettercontrolstructures
– structuredprogramming
– top-downdesignandstep-wiserefinement
 Late1970s:Process-orientedtodata-oriented
– dataabstraction
 Middle1980s:Object-orientedprogramming
– Dataabstraction+inheritance+polymorphism

6
LanguageCategories–CO1
 Imperative
– Centralfeaturesarevariables,assignmentstatements,anditeration
– Examples:C,Pascal
 Functional
– Mainmeansofmakingcomputationsisbyapplyingfunctionstogivenparameters
– Examples:LISP,Scheme
 Logic
– Rule-based(rulesarespecifiedinnoparticularorder)
– Example:Prolog
 Object-oriented
– Dataabstraction,inheritance,latebinding
– Examples:Java,C++
 Markup
– New;notaprogrammingperse,butusedtospecifythelayoutofinformationinWebdoc
uments
– Examples:XHTML,XML

LanguageDesignTrade-Offs
 Reliabilityvs.costofexecution
– Conflictingcriteria
– Example:Javademandsallreferencestoarrayelementsbecheckedforproperindexin
gbutthatleadstoincreasedexecutioncosts
 Readabilityvs.writability
– Anotherconflictingcriteria
– Example:APLprovidesmanypowerfuloperators(andalargenumberofnewsymbols
),allowingcomplexcomputationstobewritteninacompactprogrambutatthecostofp
oorreadability
 Writability(flexibility)vs.reliability
– Anotherconflictingcriteria
– Example:C++pointersarepowerfulandveryflexiblebutnotreliablyused

ImplementationMethods-CO2
 Compilation
– Programsaretranslatedintomachinelanguage
 PureInterpretation
– Programsareinterpretedbyanotherprogramknownasaninterpreter
 HybridImplementationSystems
– Acompromisebetweencompilersandpureinterpreters
Compilation
 Translatehigh-levelprogram(sourcelanguage)intomachinecode(machinelanguage)
 Slowtranslation,fastexecution
 Compilationprocesshasseveralphases:
– lexicalanalysis:convertscharactersinthesourceprogramintolexicalunits
– syntaxanalysis:transformslexicalunitsintoparsetreeswhichrepresentthesynta
cticstructureofprogram
– Semanticsanalysis:generateintermediatecode
– codegeneration:machinecodeisgenerated

7
Figure1.2LayeredViewofComputer:Theoperatingsys
temandlanguageimplementationarelayeredoverMac
hineinterfaceofacomputer Figure1.3TheCompilationProcess

AdditionalCompilationTerminologies
 Loadmodule(executableimage):theuserandsystemcodetogether
 Linkingandloading:theprocessofcollectingsystemprogramandlinkingthemtouserpro
gram
ExecutionofMachineCode
 Fetch-execute-cycle(onavonNeumannarchitecture)
initializetheprogramcounterrep
eatforever
fetchtheinstructionpointedbythecounterincrementt
hecounter
decodetheinstructionexecute
theinstruction
endrepeat
VonNeumannBottleneck
 Connectionspeedbetweenacomputer‘smemoryanditsprocessordeterminesthespeed
ofacomputer
 Programinstructionsoftencanbeexecutedalotfasterthantheaboveconnectionspee
d;theconnectionspeedthusresultsinabottleneck
 KnownasvonNeumannbottleneck;itistheprimarylimitingfactorinthespeedofcompute
rs

PureInterpretation
 Notranslation
 Easierimplementationofprograms(run-
timeerrorscaneasilyandimmediatelydisplayed)
 Slowerexecution(10to100timesslowerthancompiledprograms)
 Oftenrequiresmorespace
 Becomingrareonhigh-levellanguages

8
 Significantly comeback with some latest web scripting languages
(e.g.,JavaScript)

HybridImplementationSystems
 Acompromisebetweencompilersandpureinterpreters
 Ahigh-
levellanguageprogramistranslatedtoanintermediatelanguagethatallowseasyinterpr
etation
 Fasterthanpureinterpretation
 Examples
– Perlprogramsarepartiallycompiledtodetecterrorsbeforeinterpretation
– InitialimplementationsofJavawerehybrid;theintermediateform,bytecode,provide
sportabilitytoanymachinethathasabytecodeinterpreterandaruntimesystem(toge
ther,thesearecalledJavaVirtualMachine)

Figure1.4PureInterpreataion Figure1.5HybridImplementation

Just-in-TimeImplementationSystems
 Initiallytranslateprogramstoanintermediatelanguage
 Thencompileintermediatelanguageintomachinecode
 Machinecodeversioniskeptforsubsequentcalls
 JITsystemsarewidelyusedforJavaprograms
 .NETlanguagesareimplementedwithaJITsystem

Preprocessors-CO2
 Preprocessormacros(instructions)arecommonlyusedtospecifythatcodefromanother
fileistobeincluded
 Apreprocessorprocessesaprogramimmediatelybeforetheprogramiscompiledtoexpa
ndembeddedpreprocessormacros
 Awell-knownexample:Cpreprocessor
– expands#include,#define,andsimilarmacros

9
SyntaxandSemantics

Introduction
 Syntax:theformorstructureoftheexpressions,statements,andprogramunits
 Semantics:themeaningoftheexpressions,statements,andprogramunits
 Syntaxandsemanticsprovidealanguage‘sdefinition
– Usersofalanguagedefinition
– Otherlanguagedesigners
– Implementers
– Programmers(theusersofthelanguage)

TheGeneralProblemofDescribingSyntax–CO1
 Asentenceisastringofcharactersoversomealphabet
 Alanguageisasetofsentences
 Alexemeisthelowestlevelsyntacticunitofalanguage(e.g.,*,sum,begin)
 Atokenisacategoryoflexemes(e.g.,identifier)
 LanguagesRecognizers
– Arecognitiondevicereadsinputstringsofthelanguageanddecideswhethertheinputs
tringsbelongtothelanguage
– Example:syntaxanalysispartofacompiler
 LanguagesGenerators
– Adevicethatgeneratessentencesofalanguage
– Onecandetermineifthesyntaxofaparticularsentenceiscorrectbycomparingittothes
tructureofthegenerator

FormalMethodsofDescribingSyntax–CO1,CO2
 Backus-NaurFormandContext-FreeGrammars
– Mostwidelyknownmethodfordescribingprogramminglanguagesyntax
 ExtendedBNF
– ImprovesreadabilityandwritabilityofBNF
 GrammarsandRecognizers
Backus-NaurFormandContext-FreeGrammars
 Context-FreeGrammars
 DevelopedbyNoamChomskyinthemid-1950s
 Languagegenerators,meanttodescribethesyntaxofnaturallanguages
 Defineaclassoflanguagescalledcontext-freelanguages
Backus-NaurForm(BNF)
 Backus-NaurForm(1959)
– InventedbyJohnBackustodescribeALGOL58
– BNFisequivalenttocontext-freegrammars
– BNFisametalanguageusedtodescribeanotherlanguage
– InBNF,abstractionsareusedtorepresentclassesofsyntacticstructures--
theyactlikesyntacticvariables(alsocallednonterminalsymbols)
BNFFundamentals
 Non-terminals:BNFabstractions
 Terminals:lexemesandtokens
 Grammar:acollectionofrules
– ExamplesofBNFrules:

10
<ident_list>→identifier|identifer,<ident_list>
<if_stmt>→if<logic_expr>then<stmt>
BNFRules
 Arulehasaleft-handside(LHS)andaright-handside(RHS),andconsistsof
terminalandnonterminalsymbols
 Agrammarisafinitenonemptysetofrules
 Anabstraction(ornonterminalsymbol)canhavemorethanoneRHS
<stmt>→<single_stmt>
|begin<stmt_list>end
DescribingLists
 Syntacticlistsaredescribedusingrecursion
<ident_list>→ident
|ident,<ident_list>
 Aderivationisarepeatedapplicationofrules,startingwiththestartsymbolandendin
gwithasentence(allterminalsymbols)
AnExampleGrammar
<program>→<stmts>
<stmts>→<stmt>|<stmt>;<stmts>
<stmt> → <var> =<expr>
<var>→ a|b|c|d
<expr>→<term>+<term>|<term> -<term>
<term>→<var>|const

ParseTree
Ahierarchicalrepresentationofaderivation
Anexamplederivation Figure2.1ParseTree
<program><stmts>
 <stmt>
 <var>=<expr>
 a=<expr>
 a=<term>+<term>
 a=<var>+<term>
 a=b+<term>
 a=b+const

Derivation
 Everystringofsymbolsinthederivationisasententialform
 Asentenceisasententialformthathasonlyterminalsymbols
 Aleftmostderivationisoneinwhichtheleftmostnonterminalineachsententialformisthe
onethatisexpanded
 Aderivationmaybeneitherleftmostnorrightmost

AmbiguityinGrammars
 Agrammarisambiguousiffitgeneratesasententialformthathastwoormoredistinctpars
etrees
AnUnambiguousExpressionGrammar
Ifweusetheparsetreetoindicateprecedencelevelsoftheoperators,wecannothaveambig
uity
<expr>→<expr>-<term>|<term>
<term>→<term>/const|const

11
Figure2.2AnAmbiguousExpressionGrammar Figure2.3AnUnambiguousExpressionGr
ammar

AssociativityofOperators Figure2.4ParseTreeforAs
sociativityoperator
Operatorassociativitycanalsobeindicatedbyagra
mmar
<expr>→<expr>+<expr>|const(ambiguous)
<expr>→<expr>+const|const(unambiguous)

ExtendedBackus-NaurForm(EBNF)–CO2
 Optionalpartsareplacedinbrackets([])
<proc_call>→ident[(<expr_list>)]
 AlternativepartsofRHSsareplacedinsideparenthesesandseparatedviaverticalbar
s
<term>→<term>(+|-)const
 Repetitions(0ormore)areplacedinsidebraces({})
<ident>→letter{letter|digit}
BNFandEBNF
 BNF
<expr> → <expr>+<term>
|<expr>-<term>
|<term>
<term>→<term>*<factor>
|<term>/<factor>
|<factor>
 EBNF
<expr>→<term>{(+|-)<term>}
<term>→<factor>{(*|/)<factor>}

AttributeGrammars–CO1,CO4
 Context-
freegrammars(CFGs)cannotdescribeallofthesyntaxofprogramminglanguages
 AdditionstoCFGstocarrysomesemanticinfoalongparsetrees
 Primaryvalueofattributegrammars(AGs):
– Staticsemanticsspecification
– Compilerdesign(staticsemanticschecking)

Definition
 Anattributegrammarisacontext-
freegrammarG=(S,N,T,P)withthefollowingadditions:
– ForeachgrammarsymbolxthereisasetA(x)ofattributevalues

12
– Eachrulehasasetoffunctionsthatdefinecertainattributesofthenonterminalsint
herule
– Eachrulehasa(possiblyempty)setofpredicatestocheckforattributeconsistency
– LetX0X1...Xnbearule
– FunctionsoftheformS(X0)=f(A(X1),...,A(Xn))definesynthesizedattributes
– FunctionsoftheformI(Xj)=f(A(X0),...,A(Xn)),fori<=j<=n,define
inheritedattributes
– Initially,thereareintrinsicattributesontheleaves

Example
 Syntax
<assign>→<var>=<expr>
<expr>→<var>+<var>|<var>
<var>→A|B|C
 actual_type:synthesizedfor<var>and<expr>
 expected_type:inheritedfor<expr>
 Syntaxrule :<expr>→<var>[1]+<var>[2]
Semanticrules :<expr>.actual_type→<var>[1].actual_type
Predicate :<var>[1].actual_type==<var>[2].actual_type
<expr>.expected_type==<expr>.actual_type
 Syntaxrule :<var>→id
Semanticrule :<var>.actual_typelookup(<var>.string)
 Howareattributevaluescomputed?
– Ifallattributeswereinherited,thetreecouldbedecoratedintop-downorder.
– Ifallattributesweresynthesized,thetreecouldbedecoratedinbottom-uporder.
– Inmanycases,bothkindsofattributesareused,anditissomecombinationoftop-
downandbottom-upthatmustbeused.
<expr>.expected_typeinheritedfromparent
<var>[1].actual_typelookup(A)
<var>[2].actual_typelookup(B)
<var>[1].actual_type=?<var>[2].actual_type
<expr>.actual_type<var>[1].actual_type
<expr>.actual_type=?<expr>.expected_type

DescribingtheMeaningsofPrograms:DynamicSemantics
 Thereisnosinglewidelyacceptablenotationorformalismfordescribingsemantics
 OperationalSemantics
– Describethemeaningofaprogrambyexecutingitsstatementsonamachine,either
simulatedoractual.Thechangeinthestateofthemachine(memory,registers,etc.)
definesthemeaningofthestatement
 Touseoperationalsemanticsforahigh-levellanguage,avirtualmachineisneeded
 Ahardwarepureinterpreterwouldbetooexpensive
 Asoftwarepureinterpreteralsohasproblems:
– Thedetailedcharacteristicsoftheparticularcomputerwouldmakeactionsdifficu
lttounderstand
– Suchasemanticdefinitionwouldbemachine-dependent

13
OperationalSemantics
 Abetteralternative:Acompletecomputersimulation
 Theprocess:
– Buildatranslator(translatessourcecodetothemachinecodeofanidealizedcomputer
)
– Buildasimulatorfortheidealizedcomputer
 Evaluationofoperationalsemantics:
– Goodifusedinformally(languagemanuals,etc.)
– Extremelycomplexifusedformally(e.g.,VDL),itwasusedfordescribingsemanticsofP
L/I.
 AxiomaticSemantics
– Basedonformallogic(predicatecalculus)
– Originalpurpose:formalprogramverification
– Approach:Defineaxiomsorinferencerulesforeachstatementtypeinthelanguage(to
allowtransformationsofexpressionstootherexpressions)
– Theexpressionsarecalledassertions

AxiomaticSemantics
 Anassertionbeforeastatement(aprecondition)statestherelationshipsandconstrai
ntsamongvariablesthataretrueatthatpointinexecution
 Anassertionfollowingastatementisapostcondition
 Aweakestpreconditionistheleastrestrictivepreconditionthatwillguaranteethepostco
ndition
 Pre-postform:{P}statement{Q}
 Anexample:a=b+1{a>1}
 Onepossibleprecondition:{b>10}
 Weakestprecondition:{b>0}
 Programproofprocess:Thepostconditionforthewholeprogramisthedesiredresult.Wo
rkbackthroughtheprogramtothefirststatement.Ifthepreconditiononthefirststatemen
tisthesameastheprogramspec,theprogramiscorrect.
 Anaxiomforassignmentstatements(x=
E):
{Qx->E}x=E{Q}
 Aninferenceruleforsequences
– ForasequenceS1;S2:
– {P1}S1{P2}
– {P2}S2{P3}
 AninferenceruleforlogicalpretestloopsFort
heloopconstruct:
{P}whileBdoSend{Q}Characteristic
softheloopinvariantImustmeetthefoll
owingconditions:
– P=>I(theloopinvariantmustbetrueinitially)
– {I}B{I}(evaluationoftheBooleanmustnotchangethevalidityofI)
– {IandB}S{I}(Iisnotchangedbyexecutingthebodyoftheloop)
– (Iand(notB))=>Q(ifIistrueandBisfalse,Qisimplied)
– Theloopterminates(thiscanbedifficulttoprove)
 TheloopinvariantIisaweakenedversionofthelooppostcondition,anditisalsoaprec
ondition.

14
 Imustbeweakenoughtobesatisfiedpriortothebeginningoftheloop,butwhencombi
nedwiththeloopexitcondition,itmustbestrongenoughtoforcethetruthofthepostco
ndition.

EvaluationofAxiomaticSemantics:
– Developingaxiomsorinferencerulesforallofthestatementsinalanguageisdifficult
– Itisagoodtoolforcorrectnessproofs,andanexcellentframeworkforreasoningabout
programs,butitisnotasusefulforlanguageusersandcompilerwriters
– Itsusefulnessindescribingthemeaningofaprogramminglanguageislimitedforlangu
ageusersorcompilerwriters

DenotationalSemantics
– Basedonrecursivefunctiontheory
– Themostabstractsemanticsdescriptionmethod
– OriginallydevelopedbyScottandStrachey(1970)
– Theprocessofbuildingadenotationalspecforalanguage(notnecessarilyeasy):
– Defineamathematicalobjectforeachlanguageentity
– Defineafunctionthatmapsinstancesofthelanguageentitiesontoinstancesofthecorr
espondingmathematicalobjects
– Themeaningoflanguageconstructsaredefinedbyonlythevaluesoftheprogram'svari
ables
– Thedifferencebetweendenotationalandoperationalsemantics:Inoperationalsema
ntics,thestatechangesaredefinedbycodedalgorithms;indenotationalsemantics,the
yaredefinedbyrigorousmathematicalfunctions
– Thestateofaprogramisthevaluesofallitscurrentvariables
s={<i1,v1>,<i2,v2>,…,<in,vn>}
– LetVARMAPbeafunctionthat,whengivenavariablenameandastate,returnsthecur
rentvalueofthevariable
VARMAP(ij,s)=vj
 DecimalNumbers
– Thefollowingdenotationalsemanticsdescriptionmapsdecimalnumbersasstringsof
symbolsintonumericvalues
<dec_num>→0|1|2|3|4|5|6|7|8|9
 |<dec_num>(0|1|2|3|4|5|6|7|8|9)
Mdec('0')=0,Mdec('1')=1,…,Mdec('9')=9
Mdec(<dec_num>'0')=10*Mdec(<dec_num>)Mdec(<d
ec_num>'1’)=10*Mdec(<dec_num>)+1

Mdec(<dec_num>'9')=10*Mdec(<dec_num>)+9

Expressions
 MapexpressionsontoZ{error}
 Weassumeexpressionsaredecimalnumbers,variables,orbinaryexpressionshavingon
earithmeticoperatorandtwooperands,eachofwhichcanbeanexpression
 AssignmentStatements
– Mapsstatesetstostatesets
 LogicalPretestLoops
– Mapsstatesetstostatesets

15
 Themeaningoftheloopisthevalueoftheprogramvariablesafterthestatementsintheloo
phavebeenexecutedtheprescribednumberoftimes,assumingtherehavebeennoerrors
 Inessence,theloophasbeenconvertedfromiterationtorecursion,wheretherecursiveco
ntrolismathematicallydefinedbyotherrecursivestatemappingfunctions
 Recursion,whencomparedtoiteration,iseasiertodescribewithmathematicalrigor
 Evaluationofdenotationalsemantics
– Canbeusedtoprovethecorrectnessofprograms
– Providesarigorouswaytothinkaboutprograms
– Canbeanaidtolanguagedesign
– Hasbeenusedincompilergenerationsystems
– Becauseofitscomplexity,theyareoflittleusetolanguageusers

Summary
 BNFandcontext-freegrammarsareequivalentmeta-languages
– Well-suitedfordescribingthesyntaxofprogramminglanguages
 Anattributegrammarisadescriptiveformalismthatcandescribeboththesynta
xandthesemanticsofalanguage
 Threeprimarymethodsofsemanticsdescription
– Operation,axiomatic,denotational

16
UNIT-2
DataTypesandVariables

Introduction
 Adatatypedefinesacollectionofdataobjectsandasetofpredefinedoperationsonthoseob
jects
 Adescriptoristhecollectionoftheattributesofavariable
 Anobjectrepresentsaninstanceofauser-defined(abstractdata)type
 Onedesignissueforalldatatypes:Whatoperationsaredefinedandhowaretheyspecified
?

PrimitiveDataTypes–CO2
 Almostallprogramminglanguagesprovideasetofprimitivedatatypes
 Primitivedatatypes:Thosenotdefinedintermsofotherdatatypes
 Someprimitivedatatypesaremerelyreflectionsofthehardware
 Othersrequireonlyalittlenon-hardwaresupportfortheirimplementation
Integer
 Almostalwaysanexactreflectionofthehardwaresothemappingistrivial
 Theremaybeasmanyaseightdifferentintegertypesinalanguage
 Java‘ssignedintegersizes:byte,short,int,long
FloatingPoint
 Modelrealnumbers,butonlyasapproximations
 Languagesforscientificusesupportatleasttwofloating-
pointtypes(e.g.,floatanddouble;sometimesmore
 Usuallyexactlylikethehardware,butnotalways
 IEEEFloating-
PointStandard7
54
Complex
 Somelanguagessupportacomplextype,e.g.,FortranandPython
 Eachvalueconsistsoftwofloats,therealpartandtheimaginarypart
 Literalform(inPython):
(7+3j),where7istherealpartand3istheimaginarypart
Decimal
 Forbusinessapplications(money)
– EssentialtoCOBOL
– C#offersadecimaldatatype
 Storeafixednumberofdecimaldigits,incodedform(BCD)
 Advantage:accuracy
 Disadvantages:limitedrange,wastesmemory
Boolean
 Simplestofall
 Rangeofvalues:twoelements,onefor“true”andonefor“false”
 Couldbeimplementedasbits,butoftenasbytes
– Advantage:readability
Character
 Storedasnumericcoding
 Mostcommonlyusedcoding:ASCII
17
 Analternative,16-bitcoding:Unicode

18
– Includescharactersfrommostnaturallanguages
– OriginallyusedinJava
– C#andJavaScriptalsosupportUnicode

CharacterStringTypes
 Valuesaresequencesofcharacters
 Designissues:
– Isitaprimitivetypeorjustaspecialkindofarray?
– Shouldthelengthofstringsbestaticordynamic?
Operations
 Typicaloperations:
– Assignmentandcopying
– Comparison(=,>,etc.)
– Catenation
– Substringreference
– Patternmatching
CharacterStringTypeinCertainLanguages
 CandC++
– Notprimitive
– Usechararraysandalibraryoffunctionsthatprovideoperations
 SNOBOL4(astringmanipulationlanguage)
 Primitive
 Manyoperations,includingelaboratepatternmatching
 FortranandPython
– Primitivetypewithassignmentandseveraloperations
 Java
– PrimitiveviatheStringclass
 Perl,JavaScript,Ruby,andPHP
– Providebuilt-inpatternmatching,usingregularexpressions
CharacterStringLengthOptions
 Static:COBOL,Java‘sStringclass
 LimitedDynamicLength:CandC++
– Intheselanguages,aspecialcharacterisusedtoindicatetheendofastring‘scharact
ers,ratherthanmaintainingthelength
 Dynamic(nomaximum):SNOBOL4,Perl,JavaScript
 Adasupportsallthreestringlengthoptions
Evaluation
 Aidtowritability
 Asaprimitivetypewithstaticlength,theyareinexpensivetoprovide—
whynothavethem?
 Dynamiclengthisnice,butisitworththeexpense?
Implementation
 Staticlength:compile-timedescriptor
 Limiteddynamiclength:mayneedarun-timedescriptorforlength(butnotinCandC++)
 Dynamiclength:needrun-timedescriptor;allocation/de-
allocationisthebiggestimplementationproblem

Figure3.1Compile-TimeDescriptor Figure3.2Run-TimeDescriptors

19
User-DefinedOrdinalTypes-CO2
 Anordinaltypeisoneinwhichtherangeofpossiblevaluescanbeeasilyassociatedwith
thesetofpositiveintegers
 ExamplesofprimitiveordinaltypesinJava
– integer
– char
– boolean

EnumerationTypes
 Allpossiblevalues,whicharenamedconstants,areprovidedinthedefinition
 C#example
enumdays{mon,tue,wed,thu,fri,sat,sun};
 Designissues
– Isanenumerationconstantallowedtoappearinmorethanonetypedefinition,andifso,
howisthetypeofanoccurrenceofthatconstantchecked?
– Areenumerationvaluescoercedtointeger?
– Anyothertypecoercedtoanenumerationtype?

EvaluationofEnumeratedType
 Aidtoreadability,e.g.,noneedtocodeacolorasanumber
 Aidtoreliability,e.g.,compilercancheck:
– Operations(don‘tallowcolorstobeadded)
– Noenumerationvariablecanbeassignedavalueoutsideitsdefinedrange
– Ada,C#,andJava5.0providebettersupportforenumerationthanC++becauseenumer
ationtypevariablesintheselanguagesarenotcoercedintointegertypes

SubrangeTypes
 Anorderedcontiguoussubsequenceofanordinaltype
– Example:12..18isasubrangeofintegertype
 Ada‘sdesign
typeDaysis(mon,tue,wed,thu,fri,sat,sun);subty
peWeekdaysisDaysrangemon..fri;subtypeInde
xisIntegerrange1..100;

Day1:Days;Day
2:Weekday;Day
2:=Day1;

SubrangeEvaluation
 Aidtoreadability
– Makeitcleartothereadersthatvariablesofsubrangecanstoreonlycertainrangeofval
ues
 Reliability
– Assigningavaluetoasubrangevariablethatisoutsidethespecifiedrangeisdetecte
dasanerror

Implementation
 Enumerationtypesareimplementedasintegers
 Subrangetypesareimplementedliketheparenttypeswithcodeinserted(bythecompiler
)torestrictassignmentstosubrangevariables

20
ArrayTypes
 Anarrayisanaggregateofhomogeneousdataelementsinwhichanindividualelementisid
entifiedbyitspositionintheaggregate,relativetothefirstelement.
ArrayDesignIssues
 Whattypesarelegalforsubscripts?
 Aresubscriptingexpressionsinelementreferencesrangechecked?
 Whenaresubscriptrangesbound?
 Whendoesallocationtakeplace?
 Whatisthemaximumnumberofsubscripts?
 Canarrayobjectsbeinitialized?
 Areanykindofslicessupported?
ArrayIndexing
 Indexing(orsubscripting)isamappingfromindicestoelements
array_name(index_value_list)anelement
 IndexSyntax
– FORTRAN,PL/I,Adauseparentheses
 Adaexplicitlyusesparenthesestoshowuniformitybetweenarrayreferencesandfunctio
ncallsbecausebotharemappings
– Mostotherlanguagesusebrackets
ArraysIndex(Subscript)Types
 FORTRAN,C:integeronly
 Ada:integerorenumeration(includesBooleanandchar)
 Java:integertypesonly
 Indexrangechecking
– C,C++,Perl,andFortrandonotspecifyrangechecking
– Java,ML,C#specifyrangechecking
– InAda,thedefaultistorequirerangechecking,butitcanbeturnedoff
SubscriptBindingandArrayCategories
 Static:subscriptrangesarestaticallyboundandstorageallocationisstatic(beforerun-
time)
– Advantage:efficiency(nodynamicallocation)
 Fixedstack-
dynamic:subscriptrangesarestaticallybound,buttheallocationisdoneatdeclaratio
ntime
– Advantage:spaceefficiency
 Stack-dynamic:subscriptrangesare
dynamicallyboundandthestoragealloca
tionisdynamic(doneatrun-time)
– Advantage:flexibility(thesizeofanarrayneednotbeknownuntilthearrayistobeused
)
 Fixedheap-dynamic:similartofixedstack-
dynamic:storagebindingisdynamicbutfixedafterallocation(i.e.,bindingisdonewhenre
questedandstorageisallocatedfromheap,notstack)
 Heap-
dynamic:bindingofsubscriptrangesandstorageallocationisdynamicandcanchang
eanynumberoftimes
– Advantage:flexibility(arrayscangroworshrinkduringprogramexecution)
 CandC++arraysthatincludestaticmodifierarestatic
 CandC++arrayswithoutstaticmodifierarefixedstack-dynamic
 CandC++providefixedheap-dynamicarrays
 C#includesasecondarrayclassArrayListthatprovidesfixedheap-dynamic
21
 Perl,JavaScript,Python,andRubysupportheap-dynamicarrays

22
ArrayInitialization
 Somelanguageallowinitializationatthetimeofstorageallocation
– C,C++,Java,C#example
intlist[]={4,5,7,83}
– CharacterstringsinCandC++
charname[]=“freddie”;
– ArraysofstringsinCandC++
char*names[]={“Bob”,“Jake”,“Joe”};
– JavainitializationofStringobjects
String[]names={“Bob”,“Jake”,“Joe”};
HeterogeneousArrays
 Aheterogeneousarrayisoneinwhichtheelementsneednotbeofthesametype
 SupportedbyPerl,Python,JavaScript,andRuby
ArraysOperations
 APLprovidesthemostpowerfularrayprocessingoperationsforvectorsandmatrixesas
wellasunaryoperators(forexample,toreversecolumnelements)
 Adaallowsarrayassignmentbutalsocatenation
 Python‘sarrayassignments,buttheyareonlyreferencechanges.Pythonalsosupport
sarraycatenationandelementmembershipoperations
 Rubyalsoprovidesarraycatenation
 Fortranprovideselementaloperationsbecausetheyarebetweenpairsofarrayelements
– Forexample,+operatorbetweentwoarraysresultsinanarrayofthesumsoftheeleme
ntpairsofthetwoarrays
RectangularandJaggedArrays
 Arectangulararrayisamulti-
dimensionedarrayinwhichalloftherowshavethesamenumberofelementsandallcolum
nshavethesamenumberofelements
 Ajaggedmatrixhasrowswithvaryingnumberofelements
– Possiblewhenmulti-dimensionedarraysactuallyappearasarraysofarrays
 C,C++,andJavasupportjaggedarrays
 Fortran,Ada,andC#supportrectangulararrays(C#alsosupportsjaggedarrays)
Slices
 Asliceissomesubstructureofanarray;nothingmorethanareferencingmechanism
 Slicesareonlyusefulinlanguagesthathavearrayoperations

SliceExamples Figure3.3SlicesExamplesinFortran95
– Fortran95
Integer,Dimension(10)::VectorInteg
er,Dimension(3,3)::Mat
Integer,Dimension(3,3)::Cube

Vector(3:6)isafourelementarray

ImplementationofArrays
 Accessfunctionmapssubscriptexpressionstoanaddressinthearray
 Accessfunctionforsingle-dimensionedarrays:
address(list[k])=address(list[lower_bound])+((k-lower_bound)*element_size)

23
AccessingMulti-dimensionedArrays Figure3.4LocatinganElementina
Multi-dimensionedArray
 Twocommonways:
– Rowmajororder(byrows)–usedinmostlanguages
– Columnmajororder(bycolumns)–usedinFortran

Compile-TimeDescriptors

Figure3.5Single-DimensionedArray Figure3.6Multi-DimensionedArray

AssociativeArrays
 Anassociativearrayisanunorderedcollectionofdataelementsthatareindexedbyane
qualnumberofvaluescalledkeys
– User-definedkeysmustbestored
 Designissues:
– Whatistheformofreferencestoelements?
– Isthesizestaticordynamic?
AssociativeArraysinPerl
 Namesbeginwith%;literalsaredelimitedbyparentheses
%hi_temps=("Mon"=>77,"Tue"=>79,―Wed ‖=>65,…);
 Subscriptingisdoneusingbracesandkeys
$hi_temps{"Wed"}=83;
 Elementscanberemovedwithdelete
delete$hi_temps{"Tue"};

RecordTypes–CO2
 Arecordisapossiblyheterogeneousaggregateofdataelementsinwhichtheindividualele
mentsareidentifiedbynames
 Designissues:
– Whatisthesyntacticformofreferencestothefield?
– Areellipticalreferencesallowed?
DefinitionofRecordsinCOBOL
 COBOLuseslevelnumberstoshownestedrecords;othersuserecursivedefinition
01EMP-REC.
02EMP-NAME.
05FIRSTPICX(20).
05MIDPICX(10).
05LASTPICX(20).
02HOURLY-RATEPIC99V99.

24
DefinitionofRecordsinAda
 Recordstructuresareindicatedinanorthogonalway
typeEmp_Rec_TypeisrecordFirs
t:String(1..20);
Mid:String(1..10);
Last:String(1..20);Hourly_Ra
te:Float;
endrecord;
Emp_Rec:Emp_Rec_Type;
ReferencestoRecords
 Recordfieldreferences
– COBOL
field_nameOFrecord_name_1OF...OFrecord_name_n
– Others(dotnotation)
record_name_1.record_name_2 ....... record_name_n.field_name
 Fullyqualifiedreferencesmustincludeallrecordnames
 Ellipticalreferencesallowleavingoutrecordnamesaslongasthereferenceisunambi
guous,forexampleinCOBOL
FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are
ellipticalreferencestotheemployee‘sfirstname
OperationsonRecords
 Assignmentisverycommonifthetypesareidentical
 Adaallowsrecordcomparison
 Adarecordscanbeinitializedwithaggregateliterals
 COBOLprovidesMOVECORRESPONDING
– Copiesafieldofthesourcerecordtothecorrespondingfieldinthetargetrecord
EvaluationandComparisontoArrays
 Recordsareusedwhencollectionofdatavaluesisheterogen
eous
 Accesstoarrayelementsismuchslowerthanaccesstorec
ordfields,becausesubscriptsaredynamic(fieldnamesar
estatic)
 Dynamicsubscriptscouldbeusedwithrecordfieldaccess
,butitwoulddisallowtypecheckinganditwouldbemuchs
lower
Figure3.7ImplementationofRecordType

UnionsTypes
 Aunionisatypewhosevariablesareallowedtostoredifferenttypevaluesatdifferenttime
sduringexecution
 Designissues
– Shouldtypecheckingberequired?
– Shouldunionsbeembeddedinrecords?

Discriminatedvs.FreeUnions
 Fortran,C,andC++provideunionconstructsinwhichthereisnolanguagesupportfort
ypechecking;theunionintheselanguagesiscalledfreeunion
 Typecheckingofunionsrequirethateachunionincludeatypeindicatorcalledadiscrimina
nt
– SupportedbyAda

25
AdaUnionTypestypeS AdaUnionTypeIllustrated
hapeis(Circle,Triangle,Rectangle);typeColor
sis(Red,Green,Blue);
typeFigure(Form:Shape)isrecordFilled:Bo
olean;
Color:Colors;case
Formis
whenCircle=>Diameter:Float;
whenTriangle=>Leftside,Rightside:Integer;A
ngle:Float;
whenRectangle=>Side1,Side2:Integer;endca
se;
endrecord; Figure3.8ADiscriminatedUnionofThree
ShapeVariables
EvaluationofUnions
 Freeunionsareunsafe
– Donotallowtypechecking
 JavaandC#donotsupportunions
– Reflectiveofgrowingconcernsforsafetyinprogramminglanguage
 Ada‘sdescriminatedunionsaresafe

PointerandReferenceTypes
 Apointertypevariablehasarangeofvaluesthatconsistsofmemoryaddressesandasp
ecialvalue,nil
 Providethepowerofindirectaddressing
 Provideawaytomanagedynamicmemory
 Apointercanbeusedtoaccessalocationintheareawherestorageisdynamicallycreat
ed(usuallycalledaheap)
DesignIssuesofPointers
 Whatarethescopeofandlifetimeofapointervariable?
 Whatisthelifetimeofaheap-dynamicvariable?
 Arepointersrestrictedastothetypeofvaluetowhichtheycanpoint?
 Arepointersusedfordynamicstoragemanagement,indirectaddressing,orboth?
 Shouldthelanguagesupportpointertypes,referencetypes,orboth?
PointerOperations
 Twofundamentaloperations:assignmentanddereferencing
 Assignmentisusedtosetapointervariable‘svaluetosomeusefuladdress
 Dereferencingyieldsthevaluestoredatthelocationrepresentedbythepointer‘svalue
– Dereferencingcanbeexplicitorimplicit
– C++usesanexplicitoperationvia*
j=*ptr
setsjtothevaluelocatedatptr
PointerAssignmentIllustration

Figure3.9Theassignmentoperationj=*ptr

26
ProblemswithPointers
 Danglingpointers(dangerous)
– Apointerpointstoaheap-dynamicvariablethathasbeendeallocated
 Lostheap-dynamicvariable
– Anallocatedheap-
dynamicvariablethatisnolongeraccessibletotheuserprogram(oftencalledgarb
age)
 Pointerp1issettopointtoanewlycreatedheap-dynamicvariable
 Pointerp1islatersettopointtoanothernewlycreatedheap-dynamicvariable
 Theprocessoflosingheap-dynamicvariablesiscalledmemoryleakage
PointersinAda
 Somedanglingpointersaredisallowedbecausedynamicobjectscanbeautomatically
deallocatedattheendofpointer'stypescope
 Thelostheap-
dynamicvariableproblemisnoteliminatedbyAda(possiblewithUNCHECKED_DEAL
LOCATION)
PointersinCandC++
 Extremelyflexiblebutmustbeusedwithcare
 Pointerscanpointatanyvariableregardlessofwhenorwhereitwasallocated
 Usedfordynamicstoragemanagementandaddressing
 Pointerarithmeticispossible
 Explicitdereferencingandaddress-ofoperators
 Domaintypeneednotbefixed(void*)
void*canpointtoanytypeandcanbetypechecked(
cannotbede-referenced)
PointerArithmeticinCandC++
floatstuff[100];fl
oat*p;
p=stuff;
*(p+5)isequivalenttostuff[5]andp[5]
*(p+i)isequivalenttostuff[i]andp[i]
ReferenceTypes
 C++includesaspecialkindofpointertypecalledareferencetypethatisusedprimarilyforfo
rmalparameters
– Advantagesofbothpass-by-referenceandpass-by-value
 JavaextendsC++‘sreferencevariablesandallowsthemtoreplacepointersentirely
– Referencesarereferencestoobjects,ratherthanbeingaddresses
 C#includesboththereferencesofJavaandthepointersofC++
EvaluationofPointers
 Danglingpointersanddanglingobjectsareproblemsasisheapmanagement
 Pointersarelikegoto's--theywidentherangeofcellsthatcanbeaccessedbyavariable
 Pointersorreferencesarenecessaryfordynamicdatastructures--
sowecan'tdesignalanguagewithoutthem
RepresentationsofPointers
 Largecomputersusesinglevalues
 Intelmicroprocessorsusesegmentandoffset
DanglingPointerProblem
 Tombstone:extraheapcellthatisapointertotheheap-dynamicvariable
– Theactualpointervariablepointsonlyattombstones
– Whenheap-dynamicvariablede-allocated,tombstoneremainsbutsettonil
– Costlyintimeandspace
27
 Locks-and-keys:Pointervaluesarerepresentedas(key,address)pairs
– Heap-dynamicvariablesarerepresentedasvariablepluscellforintegerlockvalue
– Whenheap-
dynamicvariableallocated,lockvalueiscreatedandplacedinlockcellandkeycello
fpointer
HeapManagement
 Averycomplexrun-timeprocess
 Single-sizecellsvs.variable-sizecells
 Twoapproachestoreclaimgarbage
– Referencecounters(eagerapproach):reclamationisgradual
– Mark-
sweep(lazyapproach):reclamationoccurswhenthelistofvariablespacebecomesem
pty
ReferenceCounter
 Referencecounters:maintainacounterineverycellthatstorethenumberofpointerscurr
entlypointingatthecell
– Disadvantages:spacerequired,executiontimerequired,complicationsforcellsconne
ctedcircularly
– Advantage:itisintrinsicallyincremental,sosignificantdelaysintheapplicationex
ecutionareavoided
Mark-Sweep
 Therun-
timesystemallocatesstoragecellsasrequestedanddisconnectspointersfromcellsas
necessary;mark-sweepthenbegins
– Everyheapcellhasanextrabitusedbycollectionalgorithm
– Allcellsinitiallysettogarbage
– Allpointerstracedintoheap,andreachablecellsmarkedasnotgarbage
– Allgarbagecellsreturnedtolistofavailablecells
– Disadvantages:initsoriginalform,itwasdonetooinfrequently.Whendone,itcaus
edsignificantdelaysinapplicationexecution.Contemporarymarksweepalgorith
msavoidthisbydoingitmoreoften—calledincrementalmarksweep

Figure3.10MarkingAlgorithm

Variable-SizeCells
 Allthedifficultiesofsingle-sizecellsplusmore
 Requiredbymostprogramminglanguages
 Ifmark-sweepisused,additionalproblemsoccur
– Theinitialsettingoftheindicatorsofallcellsintheheapisdifficult
– Themarkingprocessinnontrivial
– Maintainingthelistofavailablespaceisanothersourceofoverhead

28
Names–CO2
 Designissuesfornames:
– Maximumlength?
– Areconnectorcharactersallowed?
– Arenamescasesensitive?
– Arespecialwordsreservedwordsorkeywords?
 Length
– Iftooshort,theycannotbeconnotative
– Languageexamples:
o FORTRANI:maximum6
o COBOL:maximum30
o FORTRAN90andANSIC:maximum31
o AdaandJava:nolimit,andallaresignificant
o C++:nolimit,butimplementorsoftenimposeone
 Connectors
– Pascal,Modula-2,andFORTRAN77don'tallow
– Othersdo
 Casesensitivity
– Disadvantage:readability(namesthatlookalikearedifferent)
o worseinC++andJavabecausepredefinednamesaremixedcase(e.g.,IndexOut
OfBoundsException)
– C,C++,andJavanamesarecasesensitive
– Thenamesinotherlanguagesarenot
 Specialwords
– Anaidtoreadability;usedtodelimitorseparatestatementclauses
– Def:Akeywordisawordthatisspecialonlyincertaincontexts
o i.e.inFortran:
– RealVarName(Realisdatatypefollowedwithaname,thereforeRealisakeyword
)
– Real=3.4(Realisavariable)
– Disadvantage:poorreadability
– Def:Areservedwordisaspecialwordthatcannotbeusedasauser-definedname

Variables–CO2
 Avariableisanabstractionofamemorycell
 Variablescanbecharacterizedasasextupleofattributes:(na
me,address,value,type,lifetime,andscope)
 Name-notallvariableshavethem(anonymous)
 Address-thememoryaddresswithwhichitisassociated(alsocalledl-value)
– Avariablemayhavedifferentaddressesatdifferenttimesduringexecution
– Avariablemayhavedifferentaddressesatdifferentplacesinaprogram
– Iftwovariablenamescanbeusedtoaccessthesamememorylocation,theyarecalle
daliases
– Aliasesareharmfultoreadability(programreadersmustrememberallofthem)
 Howaliasescanbecreated:
– Pointers,referencevariables,CandC++unions
– Someoftheoriginaljustificationsforaliasesarenolongervalid;e.g.,memoryreuse
inFORTRAN
– Replacethemwithdynamicallocation

29
 Type-
determinestherangeofvaluesofvariablesandthesetofoperationsthataredefinedforval
uesofthattype;inthecaseoffloatingpoint,typealsodeterminesthePrecision
 Value-thecontentsofthelocationwithwhichthevariableisassociated
 Abstractmemorycell-thephysicalcellorcollectionofcellsassociatedwithavariable

TheConceptofBinding
 Thel-valueofavariableisitsaddress
 Ther-valueofavariableisitsvalue
 Def:Abindingisanassociation,suchasbetweenanattributeandanentity,orbetweena
noperationandasymbol
 Def:Bindingtimeisthetimeatwhichabindingtakesplace.
 Possiblebindingtimes:
– Languagedesigntime--e.g.,bindoperatorsymbolstooperations
– Language implementation time--e.g., bind floating point type to
arepresentation
– Compiletime--e.g.,bindavariabletoatypeinCorJava
– Loadtime--e.g.,bindaFORTRAN77variabletoamemorycell(oraCstatic
variable)
– Runtime--e.g.,bindanonstaticlocalvariabletoamemorycell
 Def:Abindingisstaticifitfirstoccursbeforeruntimeandremainsunchangedthrough
outprogramexecution.
 Def:Abindingisdynamicifitfirstoccursduringexecutionorcanchangeduringexecutiono
ftheprogram.
 TypeBindings
– Howisatypespecified?
– Whendoesthebindingtakeplace?
– Ifstatic,thetypemaybespecifiedbyeitheranexplicitoranimplicitdeclaration
 Def:Anexplicitdeclarationisaprogramstatementusedfordeclaringthetypesofvariables
 Def:Animplicitdeclarationisadefaultmechanismforspecifyingtypesofvariables(thefir
stappearanceofthevariableintheprogram)
 FORTRAN,PL/I,BASIC,andPerlprovideimplicitdeclarations
– Advantage:writability
– Disadvantage:reliability(lesstroublewithPerl)
 DynamicTypeBinding(JavaScriptandPHP)
 Specifiedthroughanassignmentstatemente.g.,JavaScript
list=[2,4.33,6,8];
list=17.3;
– Advantage:flexibility(genericprogramunits)
– Disadvantages:
o Highcost(dynamictypecheckingandinterpretation)
o Typeerrordetectionbythecompilerisdifficult
 TypeInferencing(ML,Miranda,andHaskell)
– Ratherthanbyassignmentstatement,typesaredeterminedfromthecontextoftheref
erence
 StorageBindings&Lifetime
– Allocation-gettingacellfromsomepoolofavailablecells
– Deallocation-puttingacellbackintothepool

30
 Def:Thelifetimeofavariableisthetimeduringwhichitisboundtoaparticularmemory
cell
 Categoriesofvariablesbylifetimes
– Static--
boundtomemorycellsbeforeexecutionbeginsandremainsboundtothesameme
morycellthroughoutexecution.
e.g.,allFORTRAN77variables,Cstaticvariables
– Advantages: efficiency (direct addressing), history-sensitive
subprogramsupport
– Disadvantage:lackofflexibility(norecursion)
 Categoriesofvariablesbylifetimes
– Stack-dynamic--Storage bindings are created for variables when
theirdeclarationstatementsareelaborated.
– Ifscalar,allattributesexceptaddressarestaticallybound
e.g.,localvariablesinCsubprogramsandJavamethods
– Advantage:allowsrecursion;conservesstorage
– Disadvantages:
o Overheadofallocationanddeallocation
o Subprogramscannotbehistorysensitive
o Inefficientreferences(indirectaddressing)
 Categoriesofvariablesbylifetimes
– Explicit heap-dynamic--Allocated and deallocated by explicit
directives,specifiedbytheprogrammer,whichtakeeffectduringexecution
– Referencedonlythroughpointersorreferences
e.g.,dynamicobjectsinC++(vianewanddelete)allobjectsinJava
– Advantage:providesfordynamicstoragemanagement
– Disadvantage:inefficientandunreliable
 Categoriesofvariablesbylifetimes
– Implicitheapdynamic--
Allocationanddeallocationcausedbyassignmentstatements
e.g.,allvariablesinAPL;allstringsandarraysinPerlandJavaScript
– Advantage:flexibility
– Disadvantages:
o Inefficient,becauseallattributesaredynamic
o Lossoferrordetection

TypeChecking-CO3
 Generalizetheconceptofoperandsandoperatorstoincludesubprogramsandassign
ments
 Typecheckingistheactivityofensuringthattheoperandsofanoperatorareofcompatible
types
 Acompatibletypeisonethatiseitherlegalfortheoperator,orisallowedunderlanguagerul
estobeimplicitlyconverted,bycompiler-
generatedcode,toalegaltype.Thisautomaticconversioniscalledascoercion.
 Atypeerroristheapplicationofanoperatortoanoperandofaninappropriatetype
 Ifalltypebindingsarestatic,nearlyalltypecheckingcanbestatic
 Iftypebindingsaredynamic,typecheckingmustbedynamic
 Def:Aprogramminglanguageisstronglytypediftypeerrorsarealwaysdetected

31
TypeCompatibility

 Ourconcernisprimarilyforstructuredtypes
 Def:Nametypecompatibilitymeansthetwovariableshavecompatibletypesiftheyareine
itherthesamedeclarationorindeclarationsthatusethesametypename
 Easytoimplementbuthighlyrestrictive:
– Subrangesofintegertypesarenotcompatiblewithintegertypes
– Formalparametersmustbethesametypeastheircorrespondingactualparameters(P
ascal)
 Structuretypecompatibilitymeansthattwovariableshavecompatibletypesiftheirtypes
haveidenticalstructures
 Moreflexible,buthardertoimplement
 Considertheproblemoftwostructuredtypes:
– Aretworecordtypescompatibleiftheyarestructurallythesamebutusedifferentfieldna
mes?
– Aretwoarraytypescompatibleiftheyarethesameexceptthatthesubscriptsaredifferen
t?
(e.g.,[1..10]and[0..9])
– Are two enumeration types compatible if their components are
spelleddifferently?
– Withstructuraltypecompatibility,youcannotdifferentiatebetweentypesofthesamestr
ucture(e.g.,differentunitsofspeed,bothfloat)
 Languageexamples:
– Pascal:usuallystructure,butinsomecasesnameisused(formalparameters)
– C:structure,exceptforrecords
– Ada:restrictedformofname
o Derivedtypesallowtypeswiththesamestructuretobedifferent
o Anonymoustypesareallunique,evenin:
A,B:array(1..10)ofINTEGER:

StrongTyping–CO2

 Advantageofstrongtyping:allowsthedetectionofthemisusesofvariablesthatresultinty
peerrors
 Languageexamples:
– FORTRAN77isnot:parameters,EQUIVALENCE
– Pascalisnot:variantrecords
– CandC++arenot:parametertypecheckingcanbeavoided;unionsarenottypechecked
– Adais,almost(UNCHECKEDCONVERSIONisloophole)(Ja
vaissimilar)
 Coercionrulesstronglyaffectstrongtyping--
theycanweakenitconsiderably(C++versusAda)
 AlthoughJavahasjusthalftheassignmentcoercionsofC++,itsstrongtypingisstillfarle
sseffectivethanthatofAda

32
NamedConstants
 Def:Anamedconstantisavariablethatisboundtoavalueonlywhenitisboundtostora
ge
 Advantages:readabilityandmodifiability
 Usedtoparameterizeprograms
 Thebindingofvaluestonamedconstantscanbeeitherstatic(calledmanifestconstant
s)ordynamic
 Languages:
– Pascal:literalsonly
– FORTRAN90:constant-valuedexpressions
– Ada,C++,andJava:expressionsofanykind

VariableInitialization
 Def:Thebindingofavariabletoavalueatthetimeitisboundtostorageiscalledinitializatio
n
 Initializationisoftendoneonthedeclarationstatemente.g.,Javaintsum=0

Summary
 Thedatatypesofalanguagearealargepartofwhatdeterminesthatlanguage‘sstylean
dusefulness
 Theprimitivedatatypesofmostimperativelanguagesincludenumeric,charact
er,andBooleantypes
 Theuser-
definedenumerationandsubrangetypesareconvenientandaddtothereadabilityan
dreliabilityofprograms
 Arraysandrecordsareincludedinmostlanguages
 Pointersareusedforaddressingflexibilityandtocontroldynamicstoragemanage
ment
 Casesensitivityandtherelationshipofnamestospecialwordsrepresentdesignissuesof
names
 Variablesarecharacterizedbythesextuples:name,address,value,type,lifeti
me,scope
 Bindingistheassociationofattributeswithprogramentities
 Scalarvariablesarecategorizedas:static,stackdynamic,explicitheapdyna
mic,implicitheapdynamic
 Strongtypingmeansdetectingalltypeerrors

33
ExpressionsandStatements&ControlStructures

Introduction
 Expressions are the fundamental means of specifying computations in
aprogramminglanguage.
 Tounderstandexpressionevaluation,needtobefamiliarwiththeordersofoperatorandoper
andevaluation.
 EssenceofimperativelanguagesisdominantroleofassignmentstatementsArithmeticExpr
essions.
 Arithmeticevaluationwasoneofthemotivationsforthedevelopmentofthefirstprogrammi
nglanguages.

ArithmeticExpressions–CO2,CO3
Arithmetic Expressions consist of operators, operands, parentheses
andfunctioncalls.
DesignIssues
Designissuesforarithmeticexpressions
 Operatorprecedencerules?
 Operatorassociativityrules?
 Orderofoperandevaluation?
 Operandevaluationsideeffects?
 Operatoroverloading?
 Typemixinginexpressions?
Operators
 Aunaryoperatorhasoneoperand.
 Abinaryoperatorhastwooperands.
 Aternaryoperatorhasthreeoperands.
OperatorPrecedenceRules
Theoperatorprecedencerulesforexpressionevaluationdefinetheorderinwhichadjacent
operatorsofdifferentprecedencelevelsareevaluated.

Typicalprecedencelevels:
 parentheses
 unaryoperators
 **(ifthelanguagesupportsit)
 *,/
 +,-
OperatorAssociativityRule
Theoperatorassociativityrulesforexpressionevaluationdefinetheorderinwhichadjacent
operatorswiththesameprecedencelevelareevaluated.

Typicalassociativityrules:
 Lefttoright,except**(RubyandFortran),whichisrighttoleft
 Sometimesunaryoperatorsassociaterighttoleft(e.g.,inFORTRAN)
– APLisdifferent;alloperatorshaveequalprecedenceandalloperatorsassociaterightt
oleft.
– Precedenceandassociativityrulescanbeoverriddenwithparentheses.

ConditionalExpressions
34
ConditionalExpressions(ternaryoperator?:)availableinC-
basedlanguages.Anexample:(C,C++)
average=(count==0)?0:sum/count
Evaluatesasifwrittenlike
if(count==0)
average=0
else
average=sum/count
OperandEvaluationOrder
Operandevaluationorderasfollows.
 Variables:fetchthevaluefrommemory.
 Constants:sometimesafetchfrommemory;sometimestheconstantisinthemachinel
anguageinstruction.
 Parenthesizedexpressions:evaluatealloperandsandoperatorsfirst.
 Themostinterestingcaseiswhenanoperandisafunctioncall.

PotentialsforSideEffectsFunctionalsideeffects:whenafunctionchangesatwo-
wayparameteroranon-localvariable
Problemwithfunctionalsideeffects:Whenafunctionreferencedinanexpressionaltersano
theroperandoftheexpression;
e.g.,foraparameterchange:
a=10;
/*assumethatfunchangesitsparameter*/
b=a+fun(a);
Twopossiblesolutionstothefunctionalsideeffectsproblem:Writethelanguagedefinition
todisallowfunctionalsideeffects.
 Notwo-wayparametersinfunctions
 Nonon-localreferencesinfunctions

Advantage:itworks!
Disadvantages:inflexibilityofone-wayparametersandlackofnon-localreferences
– Writethelanguagedefinitiontodemandthatoperandevaluationorderbefixed.
Disadvantage:limitssomecompileroptimizations
– Javarequiresthatoperandsappeartobeevaluatedinleft-to-rightorder.

OverloadedOperators

Useofanoperatorformorethanonepurposeiscalledoperatoroverloading.
 Somearecommon(e.g.,+forintandfloat)
 Somearepotentialtrouble(e.g.,*inCandC++)
Problems:
 Lossofcompilererrordetection(omissionofanoperandshouldbeadetectableerror)
 Somelossofreadability
 Canbeavoidedbyintroductionofnewsymbols(e.g.,Pascal‘sdivforintegerdivision)
 C++,Ada,Fortran95,andC#allowuser-definedoverloadedoperators
Potentialproblems:
 Userscandefinenonsenseoperations.
 Readabilitymaysuffer,evenwhentheoperatorsmakesense.

35
TypeConversions
Anarrowingconversionisonethatconvertsanobjecttoatypethatcannotincludeallofth
evaluesoftheoriginaltype.
e.g.,floattoint
Awideningconversionisoneinwhichanobjectisconvertedtoatypethatcanincludeatleasta
pproximationstoallofthevaluesoftheoriginaltype.
e.g.,inttofloat
MixedMode
Amixed-
modeexpressionisonethathasoperandsofdifferenttypesAcoercionisanim
plicittypeconversion
Disadvantageofcoercions:
– Theydecreaseinthetypeerrordetectionabilityofthecompiler
 Inmostlanguages,allnumerictypesarecoercedinexpressions,usingwideningconve
rsions.
 InAda,therearevirtuallynocoercionsinexpressionsExplicitT
ypeConversionscalledascastinginC-basedlanguages.Examples:-
C:(int)angle,Ada:Float(Sum)
– NotethatAda’ssyntaxissimilartothatoffunctioncalls
ErrorsinExpressionscauses
 Inherentlimitationsofarithmetice.g.,divisionbyzero
 Limitationsofcomputerarithmetice.g.,overflow
 Oftenignoredbytherun-timesystem

RelationalandBooleanExpressions
RelationalExpressions:
 Userelationaloperatorsandoperandsofvarioustypes
 EvaluatetosomeBooleanrepresentation
 Operatorsymbolsusedvarysomewhatamonglanguages(!=,/=,.NE.,<>,#)
 JavaScriptandPHPhavetwoadditionalrelationaloperator,===and!==
 Similartotheircousins,==and!=,exceptthattheydonotcoercetheiroperands
BooleanExpressions:
OperandsareBooleanandtheresultisBooleanExampleop
erators
FORTRAN77 FORTRAN90 C Ada
.AND. and && and
.OR. or || or
.NOT. not ! not
xor --- --- ----
 NoBooleanTypeinC
 C89hasnoBooleantype--itusesinttypewith0forfalseandnonzerofortrue
 OneoddcharacteristicofC‘sexpressions:a<b<cisalegalexpression,buttheresultisn
otwhatyoumightexpect:
 Leftoperatorisevaluated,producing0or1
 Theevaluationresultisthencomparedwiththethirdoperand(i.e.,c)

ShortCircuitEvaluation-CO3
Anexpressioninwhichtheresultisdeterminedwithoutevaluatingalloftheoperandsand/
oroperators
Example:(13*a)*(b/13–1)
If‘a’iszero,thereisnoneedtoevaluate(b/13-1)

36
Problemwithnon-short-circuitevaluation
index=1;
while(index<=length)&&(LIST[index]!=value)index++;
 Whenindex=length,LIST[index]willcauseanindexingproblem(assumingLISThasl
ength-1elements)
 C,C++andJava:useshort-
circuitevaluationfortheusualBooleanoperators(&&and||),butalsoprovidebitwise
Booleanoperatorsthatarenotshortcircuit(&and|)
 Ada:programmercanspecifyeither(short-circuitisspecifiedwithandthenandorelse)
 Short-
circuitevaluationexposesthepotentialproblemofsideeffectsinexpressionse.g.,(a>
b)||(b++/3)

AssignmentStatementsCO3

Thegeneralsyntax:<target_var><assign_operator><expression>Thea
ssignmentoperator
 ‘=’inFORTRAN,BASIC,theC-basedlanguages
 ‘:=’inALGOL,Pascal,Ada

Equal‘=’canbebadwhenitisoverloadedfortherelationaloperatorforequality(that‘swh
ytheC-basedlanguagesuse==astherelationaloperator)
ConditionalTargets(Perl)
($flag?$total:$subtotal)=0
Whichisequivalentto
if($flag){$total=0}else
{$subtotal=0}

CompoundAssignmentOperators
 Ashorthandmethodofspecifyingacommonlyneededformofassignment.
 IntroducedinALGOL;adoptedbyCEx
:‘a=a+b’ iswrittenas‘a+=b’

UnaryAssignmentOperators
UnaryassignmentoperatorsinC-
basedlanguagescombineincrementanddecrementoperationswithassignment.Forexam
ple
sum+=++count(countincremented,addedtosum)sum+
=count++(countincremented,addedtosum)count++(co
untincremented)
-count++(countincrementedthennegated)

AssignmentasanExpression
InC,C++,andJava,theassignmentstatementproducesaresultandcanbeusedasopera
nds.
while((ch=getchar())!=EOF){…}
ch=getchar()iscarriedout;theresult(assignedtoch)isusedasaconditionalvalueforthewh
ilestatement
ListAssignments
PerlandRubysupportlistassignments
e.g.,($first,$second,$third)=(20,30,40);

37
Mixed-ModeAssignment
Assignmentstatementscanalsobemixed-mode,forexample
inta,b;float
c;
c=a/b;
– InFortran,C,andC++,anynumerictypevaluecanbeassignedtoanynumerictypevaria
ble.
– InJava,onlywideningassignmentcoercionsaredone.
– InAda,thereisnoassignmentcoercion.

ControlStructures-CO3
Acontrolstructureisacontrolstatementandthestatementswhoseexecutionitcontrols
.

LevelsofControlFlow
 Withinexpressions
 Amongprogramunits
 Amongprogramstatements

ControlStatements:Evolution
 FORTRANIcontrolstatementswerebaseddirectlyonIBM704hardware
 Muchresearchandargumentinthe1960sabouttheissue
Oneimportantresult:Itwasproventhatallalgorithmsrepresentedbyflowchartscanbecod
edwithonlytwo-wayselectionandpretestlogicalloops

SelectionStatements–CO3
Aselectionstatementprovidesthemeansofchoosingbetweentwoormorepathsofexecutio
n.Twogeneralcategories:
 Two-wayselectors
 Multiple-
wayselectorsTwo-
WaySelectionStatementsGenera
l form as follows…
ifcontrol_expressionth
enclause
elseclause
DesignIssues:
 Whatistheformandtypeofthecontrolexpression?
 Howarethethenandelseclausesspecified?
 Howshouldthemeaningofnestedselectorsbespecified?
TheControlExpression
 Ifthe‘then’reservedwordorsomeothersyntacticmarkerisnotusedtointroducethe‘then
’clause,thecontrolexpressionisplacedinparentheses.
 InC89,C99,Python,andC++,thecontrolexpressioncanbearithmetic.
 InlanguagessuchasAda,Java,Ruby,andC#,thecontrolexpressionmustbeBoolean.
ClauseForm
 Inmanycontemporarylanguages,thethenandelseclausescanbesinglestatementsorco
mpoundstatements
 InPerl,allclausesmustbedelimitedbybraces(theymustbecompound)
 InFortran95,Ada,andRuby,clausesarestatementsequences
 Pythonusesindentationtodefineclauses
38
ifx>y:
x=y
print"case1"
NestingSelectors:Javaexample
if(sum==0)if(
count==0)res
ult=0;
elseresult=1;
 Whichifgetstheelse?
 Java'sstaticsemanticsrule:elsematcheswiththenearestifNestingSelectors
 Toforceanalternativesemantics,compoundstatementsmaybeused:
if(sum==0){if(
count==0)resu
lt=0;}elseresul
t=1;
 TheabovesolutionisusedinC,C++,andC#
 Perlrequiresthatallthenandelseclausestobecompound
 Statementsequencesasclauses:Ruby
ifsum==0thenifco
unt==0thenresult
=0
elseresult
=1end
end
-Python
ifsum==0:
ifcount==0:
result=0els
e:
result=1

Multiple-WaySelectionStatements
AllowtheselectionofoneofanynumberofstatementsorstatementgroupsDesignIssues:
 Whatistheformandtypeofthecontrolexpression?
 Howaretheselectablesegmentsspecified?
 Isexecutionflowthroughthestructurerestrictedtoincludejustasingleselectablesegme
nt?
 Howarecasevaluesspecified?
 Whatisdoneaboutunrepresentedexpressionvalues?

Multiple-WaySelection:Examples
 C,C++,andJava
switch(expression){
caseconst_expr_1:stmt_1;

caseconst_expr_n:stmt_n;[defau
lt:stmt_n+1]}
 DesignchoicesforC‘sswitchstatement
 Controlexpressioncanbeonlyanintegertype
 Selectable segments can be statement sequences, blocks, or
compoundstatements
 Anynumberofsegmentscanbeexecutedinoneexecutionoftheconstruct(thereisnoimpli
citbranchattheendofselectablesegments)

39
 defaultclauseisforunrepresentedvalues(ifthereisnodefault,thewholestatementdoes
nothing)
 C#
– DiffersfromCinthatithasastaticsemanticsrulethatdisallowstheimplicitexecutio
nofmorethanonesegment
– Eachselectablesegmentmustendwithanunconditionalbranch(gotoorbreak)
 Ada
caseexpressionis
whenchoicelist=>stmt_sequence;

whenchoicelist=>stmt_sequence;w
henothers=>stmt_sequence;]endca
se;
MorereliablethanC‘sswitch(onceastmt_sequenceexecutioniscompleted,controlispassedt
othefirststatementafterthecasestatement
 Adadesignchoices:
1. Expressioncanbeanyordinaltype
2. Segmentscanbesingleorcompound
3. Onlyonesegmentcanbeexecutedperexecutionoftheconstruct
4. Unrepresentedvaluesarenotallowed
 ConstantListForms:
1. Alistofconstants
2. Caninclude:
- Subranges
- BooleanORoperators(|)

Multiple-WaySelectionUsingif
MultipleSelectorscanappearasdirectextensionstotwo-wayselectors,usingelse-
ifclauses,forexampleinPython:
ifcount<10:
bag1=Truee
lsifcount<100:
bag2=Trueels
eifcount<1000:
bag3=True

IterativeStatements
 Therepeatedexecutionofastatementorcompoundstatementisaccomplishedeitherbyit
erationorrecursion
 Generaldesignissuesforiterationcontrolstatements:
1. Howisiterationcontrolled?
2. Whereisthecontrolmechanismintheloop?
Counter-ControlledLoops
Acountingiterativestatementhasaloopvariable,andameansofspecifyingtheinitialan
dterminal,andstepsizevalues
DesignIssues:
 Whatarethetypeandscopeoftheloopvariable?
 Whatisthevalueoftheloopvariableatlooptermination?
 Shoulditbelegalfortheloopvariableorloopparameterstobechangedintheloopbody,an
difso,doesthechangeaffectloopcontrol?
 Shouldtheloopparametersbeevaluatedonlyonce,oronceforeveryiteration?

40
IterativeStatements:Examples
FORTRAN95syntax
DOlabelvar=start,finish[,stepsize]Stepsiz
ecanbeanyvaluebutzeroParameterscanbe
expressions
Designchoices:
1. LoopvariablemustbeINTEGER
2. Loopvariablealwayshasitslastvalue
3. Theloopvariablecannotbechangedintheloop,buttheparameterscan;becausetheyareeval
uatedonlyonce,itdoesnotaffectloopcontrol
4. Loopparametersareevaluatedonlyonce
 FORTRAN95:asecondform:
[name:]Dovariable=initial,terminal[,stepsize]

EndDo[name]
– CannotbranchintoeitherofFortran‘sDostatements
 Ada
forvarin[reverse]discrete_rangeloop...endl
oop
 Designchoices:
– Typeoftheloopvariableisthatofthediscreterange(Adiscreterangeisasub-
rangeofanintegerorenumerationtype).
– Loopvariabledoesnotexistoutsidetheloop
– Theloopvariablecannotbechangedintheloop,butthediscreterangecan;itdoesnotaff
ectloopcontrol
– Thediscreterangeisevaluatedjustonce
– Cannotbranchintotheloopbody
 C-basedlanguages
for([expr_1];[expr_2];[expr_3])statement
– Theexpressionscanbewholestatements,orevenstatementsequences,withthest
atementsseparatedbycommas
– Thevalueofamultiple-
statementexpressionisthevalueofthelaststatementintheexpression
– Ifthesecondexpressionisabsent,itisaninfiniteloop
 Designchoices:
– Thereisnoexplicitloopvariable
– Everythingcanbechangedintheloop
– Thefirstexpressionisevaluatedonce,buttheothertwoareevaluatedwitheachiterati
on
 C++differsfromCintwoways:
– ThecontrolexpressioncanalsobeBoolean
– Theinitialexpressioncanincludevariabledefinitions(scopeisfromthedefinitiontoth
eendoftheloopbody)
 JavaandC#
– DiffersfromC++inthatthecontrolexpressionmustbeBoolean
– IterativeStatements:Logically-ControlledLoops
– RepetitioncontrolisbasedonaBooleanexpression
 Designissues:
– Pretestorposttest?
– Shouldthelogicallycontrolledloopbeaspecialcaseofthecountingloopstatement
oraseparatestatement?

41
 IterativeStatements:Logically-ControlledLoops:Examples
CandC++havebothpretestandposttestforms,inwhichthecontrolexpressioncanbear
ithmetic:
while(ctrl_expr)doloop
bodyloopbodywhile(ctrl
_expr)
 JavaislikeCandC++,exceptthecontrolexpressionmustbeBoolean(andthebodycano
nlybeenteredatthebeginning--Javahasnogoto
 IterativeStatements:Logically-ControlledLoops:Examples
 Adahasapretestversion,butnoposttest
 FORTRAN95hasneither
 PerlandRubyhavetwopretestlogicalloops,whileanduntil.Perlalsohastwoposttestloop
s

UnconditionalBranching:User-LocatedLoopControlMechanisms
 Sometimesitisconvenientfortheprogrammerstodecidealocationforloopcontrol(other
thantoporbottomoftheloop)
 Simpledesignforsingleloops(e.g.,break)
 Designissuesfornestedloops
– Shouldtheconditionalbepartoftheexit?
– Shouldcontrolbetransferableoutofmorethanoneloop?User-
LocatedLoopControlMechanismsbreakandcontinue
 C,C++,Python,Ruby,andC#haveunconditionalunlabeledexits(break)
 JavaandPerlhaveunconditionallabeledexits(breakinJava,lastinPerl)
 C,C++,andPythonhaveanunlabeledcontrolstatement,continue,thatskipstheremai
nderofthecurrentiteration,butdoesnotexittheloop
 JavaandPerlhavelabeledversionsofcontinue
IterativeStatements:IterationBasedonDataStructures
 Numberofelementsofinadatastructurecontrolloopiteration
 Controlmechanismisacalltoaniteratorfunctionthatreturnsthenextelementinsomecho
senorder,ifthereisone;elseloopisterminate
 C'sforcanbeusedtobuildauser-definediterator:
for(p=root;p==NULL;traverse(p)){
}
 C#‘sforeachstatementiteratesontheelementsofarraysandothercollections:
Strings[]=strList={"Bob","Carol","Ted"};foreach(St
ringsnameinstrList)Console.WriteLine("Name:{0}"
,name);
Thenotation{0}indicatesthepositioninthestringtobedisplayed
 Perlhasabuilt-initeratorforarraysandhashes,foreachUnconditionalBranching
 Transfersexecutioncontroltoaspecifiedplaceintheprogram
 Representedoneofthemostheateddebatesin1960‘sand1970‘s
 Well-knownmechanism:gotostatement
 Majorconcern:Readability
 Somelanguagesdonotsupportgotostatement(e.g.,Java)
 C#offersgotostatement(canbeusedinswitchstatements)
 Loopexitstatementsarerestrictedandsomewhatcamouflagedgoto‘s

42
GuardedCommands
 DesignedbyDijkstra
 Purpose: to support a new programming methodology that
supportedverification(correctness)duringdevelopment
 Basisfortwolinguisticmechanismsforconcurrentprogramming(inCSPandAda)
 BasicIdea:iftheorderofevaluationisnotimportant,theprogramshouldnotspecifyone
SelectionGuardedCommand
• Form
if<Booleanexp>-
><statement>[]<Booleanexp>-
><statement>
...
[]<Booleanexp>-><statement>fi
Semantics:whenconstructisreached,
 EvaluateallBooleanexpressions
 Ifmorethanonearetrue,chooseonenon-deterministically
 Ifnonearetrue,itisaruntimeerror

LoopGuardedCommand
• Form
do<Boolean>-
><statement>[]<Boolean>-
><statement>
...
[]<Boolean>-><statement>Od

Semantics:foreachiteration
 EvaluateallBooleanexpressions
 Ifmorethanonearetrue,chooseonenon-deterministically;thenstartloopagain
 Ifnonearetrue,exitloop

GuardedCommands:Rationale
 Connectionbetweencontrolstatementsandprogramverificationisintimate
 Verificationisimpossiblewithgotostatements
 Verificationispossiblewithonlyselectionandlogicalpretestloops
 Verificationisrelativelysimplewithonlyguardedcommands

Summary
 Expressions
 Operatorprecedenceandassociativity
 Operatoroverloading
 Mixed-typeexpressions
 Variousformsofassignment
 Varietyofstatement-levelstructures
 Choiceofcontrolstatementsbeyondselectionandlogicalpretestloopsisatrade-
offbetweenlanguagesizeandwritability
 Functional and logic programming languages are quite different
controlstructures

43
UNIT-3
SubprogramsandBlocks

Introduction
 Twofundamentalabstractionfacilities
– Processabstraction
 Emphasizedfromearlydays
– Dataabstraction
 Emphasizedinthe1980s

FundamentalsofSubprograms–CO4
 Eachsubprogramhasasingleentrypoint
 Thecallingprogramissuspendedduringexecutionofthecalledsubprogram
 Controlalwaysreturnstothecallerwhenthecalledsubprogram‘sexecutionterminates
BasicDefinitions
 Asubprogramdefinitiondescribestheinterfacetoandtheactionsofthesubprogramabstr
action
 Asubprogramcallisanexplicitrequestthatthesubprogrambeexecuted
 Asubprogramheaderisthefirstpartofthedefinition,includingthename,thekindofsu
bprogram,andtheformalparameters
 Theparameterprofile(akasignature)ofasubprogramisthenumber,order,andtypesofits
parameters
 Theprotocolisasubprogram‘sparameterprofileand,ifitisafunction,itsreturntype
 FunctiondeclarationsinCandC++areoftencalledprototypes
 Asubprogramdeclarationprovidestheprotocol,butnotthebody,ofthesubprogram
 Aformalparameterisadummyvariablelistedinthesubprogramheaderandusedinth
esubprogram
 Anactualparameterrepresentsavalueoraddressusedinthesubprogramcallstatement
Actual/FormalParameterCorrespondence
 Positional
– Thebindingofactualparameterstoformalparametersisbyposition:thefirstactualpa
rameterisboundtothefirstformalparameterandsoforth
– Safeandeffective
 Keyword
– Thenameoftheformalparametertowhichanactualparameteristobeboundisspecifie
dwiththeactualparameter
– Parameterscanappearinanyorder
FormalParameterDefaultValues
 Incertainlanguages(e.g.,C++,Ada),formalparameterscanhavedefaultvalues(ifnotactu
alparameterispassed)
– InC++,defaultparametersmustappearlastbecauseparametersarepositionallya
ssociated
 C#methodscanacceptavariablenumberofparametersaslongastheyareofthesametype

44
ProceduresandFunctions
 Therearetwocategoriesofsubprograms
– Procedures are collection of statements that define
parameterizedcomputations
– Functionsstructurallyresembleproceduresbutaresemanticallymodeledonmat
hematicalfunctions
 Theyareexpectedtoproducenosideeffects
 Inpractice,programfunctionshavesideeffects

DesignIssuesforSubprograms-CO3
 Whatparameterpassingmethodsareprovided?
 Areparametertypeschecked?
 Arelocalvariablesstaticordynamic?
 Cansubprogramdefinitionsappearinothersubprogramdefinitions?
 Cansubprogramsbeoverloaded?
 Cansubprogrambegeneric?

ScopeandLifetime
 Thescopeofavariableistherangeofstatementsoverwhichitisvisible
 Thenonlocalvariablesofaprogramunitarethosethatarevisiblebutnotdeclaredthere
 Thescoperulesofalanguagedeterminehowreferencestonamesareassociatedwithvaria
bles
 Scopeandlifetimearesometimescloselyrelated,butaredifferentconcepts
 ConsiderastaticvariableinaCorC++function
Staticscope
– Basedonprogramtext
– Toconnectanamereferencetoavariable,you(orthecompiler)mustfindthedeclaratio
n
– Searchprocess:searchdeclarations,firstlocally,theninincreasinglylargerenclos
ingscopes,untiloneisfoundforthegivenname
– Enclosingstaticscopes(toaspecificscope)arecalleditsstaticancestors;theneares
tstaticancestoriscalledastaticparent
 Variablescanbehiddenfromaunitbyhavinga"closer"variablewiththesamename
 C++andAdaallowaccesstothese"hidden"variables
– InAda:unit.name
– InC++:class_name::name
 Blocks
– Amethodofcreatingstaticscopesinsideprogramunits--fromALGOL60
– Examples:
CandC++:for(...)
{intindex;
...
}
Ada:declareLCL:FLOAT;begin
...
end
 EvaluationofStaticScoping
 Considertheexample:
AssumeMAINcallsAandB

45
AcallsCandD
BcallsAandE
 SupposethespecischangedsothatDmustnowaccesssomedatainB
 Solutions:
– PutDinB(butthenCcannolongercallitandDcannotaccessA'svariables)
– MovethedatafromBthatDneedstoMAIN(butthenallprocedurescanaccessthem)
 Sameproblemforprocedureaccess
 Overall:staticscopingoftenencouragesmanyglobals
DynamicScope
– Basedoncallingsequencesofprogramunits,nottheirtextuallayout(temporalver
susspatial)
– Referencestovariablesareconnectedtodeclarationsbysearchingbackthroughth
echainofsubprogramcallsthatforcedexecutiontothispoint

ScopeExample
MAIN
-
declarationofx
SUB1
-declarationofx-
...
callSUB2
...SU
B2
...
-referencetox-
...
...
callSUB1

 Staticscoping
– ReferencetoxistoMAIN'sx
 Dynamicscoping
– ReferencetoxistoSUB1'sx
 EvaluationofDynamicScoping:
– Advantage:convenience
– Disadvantage:poorreadability

LocalReferencingEnvironments
 Def:Thereferencingenvironmentofastatementisthecollectionofallnamesthatarevisibl
einthestatement
 Inastatic-
scopedlanguage,itisthelocalvariablesplusallofthevisiblevariablesinalloftheenclos
ingscopes
 Asubprogramisactiveifitsexecutionhasbegunbuthasnotyetterminated
 Inadynamic-
scopedlanguage,thereferencingenvironmentisthelocalvariablesplusallvisiblevari
ablesinallactivesubprograms
 Localvariablescanbestack-dynamic(boundtostorage)
– Advantages
 Supportforrecursion
 Storageforlocalsissharedamongsomesubprograms
– Disadvantages

46
 Allocation/de-allocation,initializationtime

47
 Indirectaddressing
 Subprogramscannotbehistorysensitive
 Localvariablescanbestatic
– Moreefficient(noindirection)
– Norun-timeoverhead

ParameterPassingMethods–CO3
 Waysinwhichparametersaretransmittedtoand/orfromcalledsubprograms
– Pass-by-value
– Pass-by-result
– Pass-by-value-result
– Pass-by-reference
– Pass-by-name

Figure5.1ModelsofParameterPassing

 Thevalueoftheactualparameterisusedtoinitializethecorrespondingformalparameter
– Normallyimplementedbycopying
– Canbeimplementedbytransmittinganaccesspathbutnotrecommended(enforcing
writeprotectionisnoteasy)
– Whencopiesareused,additionalstorageisrequired
– Storageandcopyoperationscanbecostly

Pass-by-Result(OutMode)
 Whenaparameterispassedbyresult,novalueistransmittedtothesubprogram;thecorre
spondingformalparameteractsasalocalvariable;itsvalueistransmittedtocaller‘sactual
parameterwhencontrolisreturnedtothecaller
– Requireextrastoragelocationandcopyoperation
 Potentialproblem:sub(p1,p1);whicheverformalparameteriscopiedbackwillrepresen
tthecurrentvalueofp1
Pass-by-Value-Result(InoutMode)
 Acombinationofpass-by-valueandpass-by-result
 Sometimescalledpass-by-copy
 Formalparametershavelocalstorage
 Disadvantages:
– Thoseofpass-by-result
– Thoseofpass-by-value

48
Pass-by-Reference(InoutMode)
 Passanaccesspath
 Alsocalledpass-by-sharing
 Passingprocessisefficient(nocopyingandnoduplicatedstorage)
 Disadvantages
– Sloweraccesses(comparedtopass-by-value)toformalparameters
– Potentialsforun-wantedsideeffects
– Un-wantedaliases(accessbroadened)
Pass-by-Name(InoutMode)
 Bytextualsubstitution
 Formalsareboundtoanaccessmethodatthetimeofthecall,butactualbindingtoavalu
eoraddresstakesplaceatthetimeofareferenceorassignment
 Allowsflexibilityinlatebinding
ImplementingParameter-PassingMethods
 Inmostlanguageparametercommunicationtakesplacethrutherun-timestack
 Pass-by-referencearethesimplesttoimplement;onlyanaddressisplacedinthestack
 Asubtlebutfatalerrorcanoccurwithpass-by-referenceandpass-by-
valueresult:aformalparametercorrespondingtoaconstantcanmistakenlybechanged
ParameterPassingMethodsofMajorLanguages
 Fortran
– Alwaysusedtheinoutsemanticsmodel
– BeforeFortran77:pass-by-reference
– Fortran77andlater:scalarvariablesareoftenpassedbyvalue-result
 C
– Pass-by-value
– Pass-by-referenceisachievedbyusingpointersasparameters
 C++
– Aspecialpointertypecalledreferencetypeforpass-by-reference
 Java
– Allparametersarepassedarepassedbyvalue
– Objectparametersarepassedbyreference
 Ada
– Threesemanticsmodesofparametertransmission:in,out,inout;inisthedefaultm
ode
– Formalparametersdeclaredoutcanbeassignedbutnotreferenced;thosedeclaredinc
anbereferencedbutnotassigned;inoutparameterscanbereferencedandassigned
 C#
– Defaultmethod:pass-by-value
– Pass-by-
referenceisspecifiedbyprecedingbothaformalparameteranditsactualparameterw
ithref
 PHP:verysimilartoC#
 Perl:allactualparametersareimplicitlyplacedinapredefinedarraynamed@_
TypeCheckingParameters
 Consideredveryimportantforreliability
 FORTRAN77andoriginalC:none
 Pascal,FORTRAN90,Java,andAda:itisalwaysrequired

49
 ANSICandC++:choiceismadebytheuser
– Prototypes
 RelativelynewlanguagesPerl,JavaScript,andPHPdonotrequiretypechecking
MultidimensionalArraysasParameters
 Ifamultidimensionalarrayispassedtoasubprogramandthesubprogramisseparatel
ycompiled,thecompilerneedstoknowthedeclaredsizeofthatarraytobuildthestora
gemappingfunction
MultidimensionalArraysasParameters:CandC++
 Programmerisrequiredtoincludethedeclaredsizesofallbutthefirstsubscriptintheactu
alparameter
 Disallowswritingflexiblesubprograms
 Solution:passapointertothearrayandthesizesofthedimensionsasotherparameters;th
eusermustincludethestoragemappingfunctionintermsofthesizeparameters
MultidimensionalArraysasParameters:PascalandAda
 Pascal
– Notaproblem;declaredsizeispartofthearray‘stype
 Ada
– Constrainedarrays-likePascal
– Unconstrainedarrays-declaredsizeispartoftheobjectdeclaration
MultidimensionalArraysasParameters:Fortran
 Formalparameterthatarearrayshaveadeclarationaftertheheader
– Forsingle-dimensionarrays,thesubscriptisirrelevant
– Formulti-dimensionalarrays,thesubscriptsallowthestorage-mappingfunction
MultidimensionalArraysasParameters:JavaandC#
 SimilartoAda
 Arraysareobjects;theyareallsingle-dimensioned,buttheelementscanbearrays
 Eacharrayinheritsanamedconstant(lengthinJava,LengthinC#)thatissettothelengt
hofthearraywhenthearrayobjectiscreated

DesignConsiderationsforParameterPassing
 Twoimportantconsiderations
– Efficiency
– One-wayortwo-waydatatransfer
 Buttheaboveconsiderationsareinconflict
– Goodprogrammingsuggestlimitedaccesstovariables,whichmeansonewaywhenev
erpossible
– Butpass-by-referenceismoreefficienttopassstructuresofsignificantsize

ParametersSubprogramsasparameters–CO3
 Itissometimesconvenienttopasssubprogramnamesasparameters
 Issues:
– Areparametertypeschecked?
– Whatisthecorrectreferencingenvironmentforasubprogramthatwassentasaparam
eter?
ParametersthatareSubprogramNames:ParameterTypeChecking
 CandC++:functionscannotbepassedasparametersbutpointerstofunctionscanbepasse
d;parameterscanbetypechecked
 FORTRAN95typechecks

50
 LaterversionsofPascaland
 Adadoesnotallowsubprogramparameters;asimilaralternativeisprovidedviaAda‘sgen
ericfacility
ParametersthatareSubprogramNames:ReferencingEnvironment
 Shallowbinding:Theenvironmentofthecallstatementthatenactsthepassedsubprogra
m
 Deepbinding:Theenvironmentofthedefinitionofthepassedsubprogram
 Adhocbinding:Theenvironmentofthecallstatementthatpassedthesubprogram
OverloadedSubprograms–CO3
 Anoverloadedsubprogramisonethathasthesamenameasanothersubprograminthe
samereferencingenvironment
– Everyversionofanoverloadedsubprogramhasauniqueprotocol
 C++,Java,C#,andAdaincludepredefinedoverloadedsubprograms
 InAda,thereturntypeofanoverloadedfunctioncanbeusedtodisambiguatecalls(thu
stwooverloadedfunctionscanhavethesameparameters)
 Ada,Java,C++,andC#allowuserstowritemultipleversionsofsubprogramswiththes
amename
GenericSubprograms–CO3
 Agenericorpolymorphicsubprogramtakesparametersofdifferenttypesondifferentacti
vations
 Overloadedsubprogramsprovideadhocpolymorphism
 Asubprogramthattakesagenericparameterthatisusedinatypeexpressionthatdesc
ribesthetypeoftheparametersofthesubprogramprovidesparametricpolymorphis
m
Examplesofparametricpolymorphism:C++
template<classType>
Typemax(Typefirst,Typesecond){retu
rnfirst>second?first:second;
}
 Theabovetemplatecanbeinstantiatedforanytypeforwhichoperator>isdefined
intmax(intfirst,intsecond){returnfirs
t>second?first:second;
}
DesignIssuesforFunctions
 Aresideeffectsallowed?
– Parametersshouldalwaysbein-modetoreducesideeffect(likeAda)
 Whattypesofreturnvaluesareallowed?
– Mostimperativelanguagesrestrictthereturntypes
– Callowsanytypeexceptarraysandfunctions
– C++islikeCbutalsoallowsuser-definedtypes
– Adaallowsanytype
– JavaandC#donothavefunctionsbutmethodscanhaveanytype
User-DefinedOverloadedOperators
 OperatorscanbeoverloadedinAdaandC++
 AnAdaexample
Function“*”(A,B:inVec_Type):returnIntegerisSum
:Integer:=0;
begin
forIndexinA‘rangeloop
Sum:=Sum+A(Index)*B(Index)endlo
op

51
returnsum;
end“*”;

c=a*b;--a,b,andcareoftypeVec_Type
Co-Routines–CO3
 Acoroutineisasubprogramthathasmultipleentriesandcontrolsthemitself
 Alsocalledsymmetriccontrol:callerandcalledcoroutinesareonamoreequalbasis
 Acoroutinecallisnamedaresume
 Thefirstresumeofacoroutineistoitsbeginning,butsubsequentcallsenteratthepoint
justafterthelastexecutedstatementinthecoroutine
 Coroutinesrepeatedlyresumeeachother,possiblyforever
 Coroutinesprovidequasi-
concurrentexecutionofprogramunits(thecoroutines);theirexecutionisinterleaved,but
notoverlapped

Figure5.2PossibleExecutionControls Figure5.3PossibleExecutionControls

Figure5.4PossibleExecutionControlswithLoops
Summary
 Asubprogramdefinitiondescribestheactionsrepresentedbythesubprogram
 Subprogramscanbeeitherfunctionsorprocedures
 Localvariablesinsubprogramscanbestack-dynamicorstatic
 Threemodelsofparameterpassing:inmode,outmode,andinoutmode
 Somelanguagesallowoperatoroverloading
 Subprogramscanbegeneric
 Aco-routineisaspecialsubprogramwithmultipleentries

52
UNIT-4
AbstractDataTypes

TheConceptofAbstraction–CO3
 Anabstractionisavieworrepresentationofanentitythatincludesonlythemostsignifican
tattributes
 Theconceptofabstractionisfundamentalinprogramming(andcomputerscience)
 Nearly all programming languages support process abstraction
withsubprograms
 Nearlyallprogramminglanguagesdesignedsince1980supportdataabstraction

IntroductiontoDataAbstraction–CO3
 AnAbstractDataTypeisauser-
defineddatatypethatsatisfiesthefollowingtwoconditions:
– Therepresentationof,andoperationson,objectsofthetypearedefinedinasinglesynta
cticunit
– Therepresentationofobjectsofthetypeishiddenfromtheprogramunitsthatusethes
eobjects,sotheonlyoperationspossiblearethoseprovidedinthetype'sdefinition

AdvantagesofDataAbstraction
 Advantageofthefirstcondition
– Programorganization,modifiability(everythingassociatedwithadatastructurei
stogether),andseparatecompilation
 Advantagethesecondcondition
– Reliability--
byhidingthedatarepresentations,usercodecannotdirectlyaccessobjectsofthetype
ordependontherepresentation,allowingtherepresentationtobechangedwithoutaf
fectingusercode
LanguageRequirementsforADTs:
 Asyntacticunitinwhichtoencapsulatethetypedefinition
 Amethodofmakingtypenamesandsubprogramheadersvisibletoclients,whilehidingac
tualdefinitions
 SomeprimitiveoperationsmustbebuiltintothelanguageprocessorDesignI
ssues:
 Canabstracttypesbeparameterized?
 Whataccesscontrolsareprovided?

LanguageExamplesCO2,CO3,CO4
LanguageExamples:Ada
 Theencapsulationconstructiscalledapackage
– Specificationpackage(theinterface)
– Bodypackage(implementationoftheentitiesnamedinthespecification)
 InformationHiding
– Thespecpackagehastwoparts,publicandprivate
– Thenameoftheabstracttypeappearsinthepublicpartofthespecificationpackage.Thi
spartmayalsoincluderepresentationsofunhiddentypes

53
– Therepresentationoftheabstracttypeappearsinapartofthespecificationcalledthep
rivatepart
 Morerestrictedformwithlimitedprivatetypes
– Privatetypeshavebuilt-inoperationsforassignmentandcomparison
– LimitedprivatetypeshaveNObuilt-inoperations
 Reasonsforthepublic/privatespecpackage:
1. Thecompilermustbeabletoseetherepresentationafterseeingonlythespecpacka
ge(itcannotseetheprivatepart)
2. Clientsmustseethetypename,butnottherepresentation(theyalsocannotseethe
privatepart)
 Havingpartoftheimplementationdetails(therepresentation)inthespecpackageandpa
rt(themethodbodies)inthebodypackageisnotgood

Onesolution:makeallADTspointers
Problemswiththis:
1. Difficultieswithpointers
2. Objectcomparisons
3. ControlofobjectallocationislostAnE
xampleinAda
packageStack_Packis
typestack_typeislimitedprivate;max_size:
constant:=100;
functionempty(stk:instack_type)returnBoolean;procedurepu
sh(stk:inoutstack_type;elem:inInteger);procedurepop(stk:in
outstack_type);
functiontop(stk:instack_type)returnInteger;private--
hiddenfromclients
typelist_typeisarray(1..max_size)ofInteger;typesta
ck_typeisrecord
list:list_type;
topsub:Integerrange0..max_size):=0;end
record;
endStack_Pack

LanguageExamples:C++
 BasedonCstructtypeandSimula67classes
 Theclassistheencapsulationdevice
 Alloftheclassinstancesofaclassshareasinglecopyofthememberfunctions
 Eachinstanceofaclasshasitsowncopyoftheclassdatamembers
 Instancescanbestatic,stackdynamic,orheapdynamic
 InformationHiding
– Privateclauseforhiddenentities
– Publicclauseforinterfaceentities
– Protectedclauseforinheritance(Chapter12)
 Constructors:
– Functionstoinitializethedatamembersofinstances(theydonotcreatetheobjects)
– Mayalsoallocatestorageifpartoftheobjectisheap-dynamic
– Canincludeparameterstoprovideparameterizationoftheobjects
– Implicitlycalledwhenaninstanceiscreated
– Canbeexplicitlycalled

54
– Nameisthesameastheclassname
 Destructors
– Functionstocleanupafteraninstanceisdestroyed;usuallyjusttoreclaimheapstor
age
– Implicitlycalledwhentheobject‘slifetimeends
– Canbeexplicitlycalled
– Nameistheclassname,precededbyatilde(~)AnExa
mpleinC++
classstack{
private:
int*stackPtr,maxLen,topPtr;pu
blic:
stack(){//aconstructorstackPt
r=newint[100];maxLen=99
;
topPtr=-1;
};
~stack(){delete[]stackPtr;};voi
dpush(intnum){…};voidpop(){
…};
inttop(){…};
intempty(){…};
}
EvaluationofADTsinC++andAda
 C++supportforADTsissimilartoexpressivepowerofAda
 Bothprovideeffectivemechanismsforencapsulationandinformationhiding
 Adapackagesaremoregeneralencapsulations;classesaretypes
 Friendfunctionsorclasses-
toprovideaccesstoprivatememberstosomeunrelatedunitsorfunctions
– NecessaryinC++
LanguageExamples:Java
 SimilartoC++,except:
– Alluser-definedtypesareclasses
– Allobjectsareallocatedfromtheheapandaccessedthroughreferencevariables
– Individualentitiesinclasseshaveaccesscontrolmodifiers(privateorpublic),rathert
hanclauses
– Javahasasecondscopingmechanism,packagescope,whichcanbeusedinplaceoff
riends
 Allentitiesinallclassesinapackagethatdonothaveaccesscontrolmodifiersarevisibl
ethroughoutthepackage
AnExampleinJava
classStackClass{priva
te:
privateint[]*stackRef;
privateint[]maxLen,topIndex;publicSt
ackClass(){//aconstructor
stackRef=newint[100];ma
xLen=99;
topPtr=-1;
};
public void push (int num)
{…};public void pop () {…};
publicinttop(){…};
publicbooleanempty(){…};
}

55
LanguageExamples:C#
 BasedonC++andJava
 Addstwoaccessmodifiers,internalandprotectedinternal
 Allclassinstancesareheapdynamic
 Defaultconstructorsareavailableforallclasses
 Garbagecollectionisusedformostheapobjects,sodestructorsarerarelyused
 structsarelightweightclassesthatdonotsupportinheritance
 Commonsolutiontoneedforaccesstodatamembers:accessormethods(getterandsetter
)
 C#providespropertiesasawayofimplementinggettersandsetterswithoutrequiringexp
licitmethodcalls

C#PropertyExample
publicclassWeather{
publicintDegreeDays{//**DegreeDaysisapropertyget{ret
urndegreeDays;}
set{
if(value<0||value>30)
Console.WriteLine("Valueisoutofrange:{0}",value);elsede
greeDays=value;}
}
privateintdegreeDays;
...
}
...
Weatherw=newWeather();
intdegreeDaysToday,oldDegreeDays;
...
w.DegreeDays=degreeDaysToday;
...
oldDegreeDays=w.DegreeDays;

ParameterizedAbstractDataTypes-CO4
 ParameterizedADTsallowdesigninganADTthatcanstoreanytypeelements(amongoth
erthings)
 Alsoknownasgenericclasses
 C++,Ada,Java5.0,andC#2005providesupportforparameterizedADTs
ParameterizedADTsinAda
 AdaGenericPackages
– Makethestacktypemoreflexiblebymakingtheelementtypeandthesizeofthestackge
neric
generic
Max_Size:Positive;
typeElem_Typeisprivate;packa
geGeneric_Stackis
TypeStack_Typeislimitedprivate;
functionTop(Stk:inoutStackType)returnElem_type;

endGeneric_Stack;
PackageInteger_StackisnewGeneric_Stack(100,Integer);Package
Float_StackisnewGeneric_Stack(100,Float);
ParameterizedADTsinC++
 Classes can be somewhat generic by writing parameterized
constructorfunctions
classstack{

56
stack(intsize){stk_ptr=n
ewint[size];max_len=siz
e-1;
top=-1;
};

}
stackstk(100);
 Thestackelementtypecanbeparameterizedbymakingtheclassatemplatedclass
template<classType>cla
ssstack{
private:
Type*stackPtr;const
intmaxLen;inttopPt
r;
public:
stack(){
stackPtr=newType[100];m
axLen=99;
topPtr=-1;
}

}
ParameterizedClassesinJava5.0
 Genericparametersmustbeclasses
 Mostcommongenerictypesarethecollectiontypes,suchasLinkedListandArrayList
 Eliminatetheneedtocastobjectsthatareremoved
 Eliminatetheproblemofhavingmultipletypesinastructure
ParameterizedClassesinC#2005
 SimilartothoseofJava5.0
 Elementsofparameterizedstructurescanbeaccessedthroughindexing
SummaryofADT
 TheconceptofADTsandtheiruseinprogramdesignwasamilestoneinthedevelopmentof
languages
 TwoprimaryfeaturesofADTsarethepackagingofdatawiththeirassociatedoperationsa
ndinformationhiding
 AdaprovidespackagesthatsimulateADTs
 C++dataabstractionisprovidedbyclasses
 Java‘sdataabstractionissimilartoC++
 Ada,C++,Java5.0,andC#2005supportparameterizedADTs

Object-OrientedProgramming–CO4
 Abstractdatatypes
 Inheritance
– InheritanceisthecentralthemeinOOPandlanguagesthatsupportit
 Polymorphism
Inheritance
 Productivityincreasescancomefromreuse
– ADTsaredifficulttoreuse—alwaysneedchanges
– AllADTsareindependentandatthesamelevel
 Inheritanceallowsnewclassesdefinedintermsofexistingones,i.e.,byallowingthemtoin
heritcommonparts

57
 Inheritanceaddressesbothoftheaboveconcerns--
reuseADTsafterminorchangesanddefineclassesinahierarchy
Object-OrientedConcepts
 ADTsareusuallycalledclasses
 Classinstancesarecalledobjects
 Aclassthatinheritsisaderivedclassorasubclass
 Theclassfromwhichanotherclassinheritsisaparentclassorsuperclass
 Subprogramsthatdefineoperationsonobjectsarecalledmethods
 Callstomethodsarecalledmessages
 Theentirecollectionofmethodsofanobjectiscalleditsmessageprotocolor
messageinterface
 Messageshavetwoparts--amethodnameandthedestinationobject
 Inthesimplestcase,aclassinheritsalloftheentitiesofitsparent
 Inheritancecanbecomplicatedbyaccesscontrolstoencapsulatedentities
– Aclasscanhideentitiesfromitssubclasses
– Aclasscanhideentitiesfromitsclients
– Aclasscanalsohideentitiesforitsclientswhileallowingitssubclassestoseethem
 Besidesinheritingmethodsasis,aclasscanmodifyaninheritedmethod
– Thenewoneoverridestheinheritedone
– Themethodintheparentisoverriden
 Therearetwokindsofvariablesinaclass:
– Classvariables-one/class
– Instancevariables-one/object
 Therearetwokindsofmethodsinaclass:
– Classmethods–acceptmessagestotheclass
– Instancemethods–acceptmessagestoobjects
 Singlevs.MultipleInheritance
 Onedisadvantageofinheritanceforreuse:
– Createsinterdependenciesamongclassesthatcomplicatemaintenance
DynamicBinding
 Apolymorphicvariablecanbedefinedinaclassthatisabletoreference(orpointto)objects
oftheclassandobjectsofanyofitsdescendants
 Whenaclasshierarchyincludesclassesthatoverridemethodsandsuchmethodsarecalle
dthroughapolymorphicvariable,thebindingtothecorrectmethodwillbedynamic
 Allowssoftwaresystemstobemoreeasilyextendedduringbothdevelopmentandmainte
nance
DynamicBindingConcepts
 Anabstractmethodisonethatdoesnotincludeadefinition(itonlydefinesaprotocol)
 Anabstractclassisonethatincludesatleastonevirtualmethod
 Anabstractclasscannotbeinstantiated

DesignIssuesforOOPLanguages–CO4
 TheExclusivityofObjects
 AreSubclassesSubtypes?
 TypeCheckingandPolymorphism
 SingleandMultipleInheritance
 ObjectAllocationandDeAllocation

58
 DynamicandStaticBinding
 NestedClasses
TheExclusivityofObjects
 Everythingisanobject
– Advantage-eleganceandpurity
– Disadvantage-slowoperationsonsimpleobjects
 Addobjectstoacompletetypingsystem
– Advantage-fastoperationsonsimpleobjects
– Disadvantage-resultsinaconfusingtypesystem(twokindsofentities)
 Includeanimperative-styletypingsystemforprimitivesbutmakeeverythingelseobjects
– Advantage-fastoperationsonsimpleobjectsandarelativelysmalltypingsystem
– Disadvantage-stillsomeconfusionbecauseofthetwotypesystems
AreSubclassesSubtypes?
 Doesan“is-
a”relationshipholdbetweenaparentclassobjectandanobjectofthesubclass?
– Ifaderivedclassis-
aparentclass,thenobjectsofthederivedclassmustbehavethesameastheparentclass
object
 Aderivedclassisasubtypeifithasanis-arelationshipwithitsparentclass
– Subclasscanonlyaddvariablesandmethodsandoverrideinheritedmethodsin
“compatible”ways
TypeCheckingandPolymorphism
 Polymorphismmayrequiredynamictypecheckingofparametersandthereturnvalue
– Dynamictypecheckingiscostlyanddelayserrordetection
 Ifoverridingmethodsarerestrictedtohavingthesameparametertypesandreturntype,t
hecheckingcanbestatic
SingleandMultipleInheritance
 Multipleinheritanceallowsanewclasstoinheritfromtwoormoreclasses
 Disadvantagesofmultipleinheritance:
– Languageandimplementationcomplexity(inpartduetonamecollisions)
– Potentialinefficiency-
dynamicbindingcostsmorewithmultipleinheritance(butnotmuch)
 Advantage:
– Sometimesitisquiteconvenientandvaluable
AllocationandDeAllocationofObjects
 Fromwhereareobjectsallocated?
– IftheybehavelinetheADTs,theycanbeallocatedfromanywhere
 Allocatedfromtherun-timestack
 Explicitlycreateontheheap(vianew)
– Iftheyareallheap-
dynamic,referencescanbeuniformthruapointerorreferencevariable
 Simplifiesassignment-dereferencingcanbeimplicit
– Ifobjectsarestackdynamic,thereisaproblemwithregardtosubtypes
 Isdeallocationexplicitorimplicit?
DynamicandStaticBinding
 Shouldallbindingofmessagestomethodsbedynamic?
– Ifnoneare,youlosetheadvantagesofdynamicbinding
– Ifallare,itisinefficient
 Allowtheusertospecify

59
NestedClasses
 Ifanewclassisneededbyonlyoneclass,thereisnoreasontodefinesoitcanbeseenbyother
classes
– Canthenewclassbenestedinsidetheclassthatusesit?
– Insomecases,thenewclassisnestedinsideasubprogramratherthandirectlyinan
otherclass
 Otherissues:
– Whichfacilitiesofthenestingclassshouldbevisibletothenestedclassandviceversa

SupportforOOPinSmalltalk–CO4
 SmalltalkisapureOOPlanguage
– Everythingisanobject
– Allobjectshavelocalmemory
– Allcomputationisthroughobjectssendingmessagestoobjects
– Noneoftheappearancesofimperativelanguages
– Allobjectedareallocatedfromtheheap
– Alldeallocationisimplicit
 TypeCheckingandPolymorphism
– Allbindingofmessagestomethodsisdynamic
 Theprocessistosearchtheobjecttowhichthemessageissentforthemethod;ifnotfou
nd,searchthesuperclass,etc.uptothesystemclasswhichhasnosuperclass
– TheonlytypecheckinginSmalltalkisdynamicandtheonlytypeerroroccurswhen
amessageissenttoanobjectthathasnomatchingmethod
 Inheritance
– ASmalltalksubclassinheritsalloftheinstancevariables,instancemethods,andcla
ssmethodsofitssuperclass
– Allsubclassesaresubtypes(nothingcanbehidden)
– Allinheritanceisimplementationinheritance
– Nomultipleinheritance
 EvaluationofSmalltalk
– Thesyntaxofthelanguageissimpleandregular
– Goodexampleofpowerprovidedbyasmalllanguage
– Slowcomparedwithconventionalcompiledimperativelanguages
– Dynamicbindingallowstypeerrorstogoundetecteduntilruntime
– Introducedthegraphicaluserinterface
– Greatestimpact:advancementofOOP

SupportforOOPinC++-CO4
 GeneralCharacteristics:
– EvolvedfromCandSIMULA67
– AmongthemostwidelyusedOOPlanguages
– Mixedtypingsystem
– Constructorsanddestructors
– Elaborateaccesscontrolstoclassentities
 Inheritance
– Aclassneednotbethesubclassofanyclass
– Accesscontrolsformembersare
– Private(visibleonlyintheclassandfriends)(disallowssubclassesfrombeingsubtype
s)

60
– Public(visibleinsubclassesandclients)
– Protected(visibleintheclassandinsubclasses,butnotclients)
 Inaddition,thesubclassingprocesscanbedeclaredwithaccesscontrols(privateorpu
blic),whichdefinepotentialchangesinaccessbysubclasses
– Privatederivation-
inheritedpublicandprotectedmembersareprivateinthesubclasses
– Public derivation public and protected members are also public
andprotectedinsubclasses
InheritanceExampleinC++
classbase_class{priva
te:
inta;float
x;
protected:
intb;floa
ty;public
:intc;floa
tz;
};
classsubclass_1:publicbase_class{…};
//Inthisone,bandyareprotectedand
//candzarepublic
classsubclass_2:privatebase_class{…};
//Inthisone,b,y,c,andzareprivate,
//andnoderivedclasshasaccesstoany
//memberofbase_class
 Amemberthatisnotaccessibleinasubclass(becauseofprivatederivation)canbedeclare
dtobevisiblethereusingthescoperesolutionoperator(::),e.g.,
classsubclass_3:privatebase_class{base_cl
ass::c;

}
 Onemotivationforusingprivatederivation
– Aclassprovidesmembersthatmustbevisible,sotheyaredefinedtobepublicmembers
;aderivedclassaddssomenewmembers,butdoesnotwantitsclientstoseethemembe
rsoftheparentclass,eventhoughtheyhadtobepublicintheparentclassdefinition
 Multipleinheritanceissupported
– Iftherearetwoinheritedmemberswiththesamename,theycanbothbereferencedusi
ngthescoperesolutionoperator
 DynamicBinding
– Amethodcanbedefinedtobevirtual,whichmeansthattheycanbecalledthroughp
olymorphicvariablesanddynamicallyboundtomessages
– Apurevirtualfunctionhasnodefinitionatall
– Aclassthathasatleastonepurevirtualfunctionisanabstractclass
 Evaluation
– C++providesextensiveaccesscontrols(unlikeSmalltalk)
– C++providesmultipleinheritance
– InC++,theprogrammermustdecideatdesigntimewhichmethodswillbestatically
boundandwhichmustbedynamicallybound
 Staticbindingisfaster!
– Smalltalktypecheckingisdynamic(flexible,butsomewhatunsafe)
– Becauseofinterpretationanddynamicbinding,Smalltalkis~10timesslowerthanC+
+

61
SupportforOOPinJava–CO4
 BecauseofitscloserelationshiptoC++,focusisonthedifferencesfromthatlanguage
 GeneralCharacteristics
– Alldataareobjectsexcepttheprimitivetypes
– Allprimitivetypeshavewrapperclassesthatstoreonedatavalue
– Allobjectsareheap-
dynamic,arereferencedthroughreferencevariables,andmostareallocatedwithnew
– Afinalizemethodisimplicitlycalledwhenthegarbagecollectorisabouttoreclaimthes
torageoccupiedbytheobject
 Inheritance
– Singleinheritancesupportedonly,butthereisanabstractclasscategorythatprovi
dessomeofthebenefitsofmultipleinheritance(interface)
– Aninterfacecanincludeonlymethoddeclarationsandnamedconstants,
e.g.,
publicinterfaceComparable{
publicintcomparedTo(Objectb);}
– Methodscanbefinal(cannotbeoverriden)
 DynamicBinding
– InJava,allmessagesaredynamicallyboundtomethods,unlessthemethodisfinal(i.
e.,itcannotbeoverriden,thereforedynamicbindingservesnopurpose)
– Staticbindingisalsousedifthemethodsisstaticorprivatebothofwhichdisallowoverri
ding
 Severalvarietiesofnestedclasses
 Allarehiddenfromallclassesintheirpackage,exceptforthenestingclass
 Nestedclassescanbeanonymous
 Alocalnestedclassisdefinedinamethodofitsnestingclass
– Noaccessspecifierisused
 Evaluation
– DesigndecisionstosupportOOParesimilartoC++
– Nosupportforproceduralprogramming
– Noparentlessclasses
– Dynamicbindingisusedas“normal”waytobindmethodcallstomethoddefinitions
– Usesinterfacestoprovideasimpleformofsupportformultipleinheritance

SupportforOOPinC#-CO4
 Generalcharacteristics
– SupportforOOPsimilartoJava
– Includesbothclassesandstructs
– ClassesaresimilartoJava‘sclasses
– structsarelesspowerfulstack-dynamicconstructs(e.g.,noinheritance)
 Inheritance
– UsesthesyntaxofC++fordefiningclasses
– Amethodinheritedfromparentclasscanbereplacedinthederivedclassbymarkingits
definitionwithnew
– Theparentclassversioncanstillbecalledexplicitlywiththeprefixbase:base.Draw()
 Dynamicbinding
– Toallowdynamicbindingofmethodcallstomethods:

62
 Thebaseclassmethodismarkedvirtual
 Thecorrespondingmethodsinderivedclassesaremarkedoverride
– Abstractmethodsaremarkedabstractandmustbeimplementedinallsubclasses
– AllC#classesareultimatelyderivedfromasinglerootclass,Object
 NestedClasses
– AC#classthatisdirectlynestedinanestingclassbehaveslikeaJavastaticnestedcla
ss
– C#doesnotsupportnestedclassesthatbehavelikethenon-staticclassesofJava
 Evaluation
– C#isthemostrecentlydesignedC-basedOOlanguage
– ThedifferencesbetweenC#‘sandJava‘ssupportforOOParerelativelyminor

SupportforOOPinAda95–CO4
 GeneralCharacteristics
– OOPwasoneofthemostimportantextensionstoAda83
– Encapsulationcontainerisapackagethatdefinesataggedtype
– Ataggedtypeisoneinwhicheveryobjectincludesatagtoindicateduringexecutionitst
ype(thetagsareinternal)
– Taggedtypescanbeeitherprivatetypesorrecords
– Noconstructorsordestructorsareimplicitlycalled
 Inheritance
– Subclassescanbederivedfromtaggedtypes
– Newentitiesareaddedtotheinheritedentitiesbyplacingtheminarecorddefinition
– Allsubclassesaresubtypes
– Nosupportformultipleinheritance
 AcomparableeffectcanbeachievedusinggenericclassesExamp
leofaTaggedType
PackagePerson_Pkgis
typePersonistaggedprivate;procedure
Display(P:inoutPerson);
private
typePersonistaggedreco
rd
Name:String(1..30);Addr
ess:String(1..30);Age:Int
eger;
endrecord;en
dPerson_Pkg;
withPerson_Pkg;usePerson_Pkg;packag
eStudent_Pkgis
typeStudentisnewPersonwithreco
rd
Grade_Point_Average:Float;G
rade_Level:Integer;
endrecord;
procedureDisplay(St:inStudent);e
ndStudent_Pkg;
//Note:DisplayisbeingoverriddenfromPerson_Pkg
 DynamicBinding
– Dynamicbindingisdoneusingpolymorphicvariablescalledclasswidetypes
 ForthetaggedtypePrtdon,theclasswidetypeisPerson‘class
– Otherbindingsarestatic

63
– Anymethodmaybedynamicallybound
– PurelyabstractbasetypescanbedefinedinAda95byincludingthereservedworda
bstract
 Evaluation
– AdaofferscompletesupportforOOP
– C++offersbetterformofinheritancethanAda
– Adaincludesnoinitializationofobjects(e.g.,constructors)
– DynamicbindinginC-
basedOOPlanguagesisrestrictedtopointersand/orreferencestoobjects;Adahasnos
uchrestrictionandisthusmoreorthogonal

ImplementingOOPsConstructs
 Twointerestingandchallengingparts
– Storagestructuresforinstancevariables
– Dynamicbindingofmessagestomethods
InstanceDataStorage
 Classinstancerecords(CIRs)storethestateofanobject
– Static(builtatcompiletime)
 Ifaclasshasaparent,thesubclassinstancevariablesareaddedtotheparentCIR
 BecauseCIRisstatic,accesstoallinstancevariablesisdoneasitisinrecords
– Efficient
DynamicBindingofMethodsCalls
 MethodsinaclassthatarestaticallyboundneednotbeinvolvedintheCIR;methodstha
twillbedynamicallyboundmusthaveentriesintheCIR
– Callstodynamicallyboundmethodscanbeconnectedtothecorrespondingcodethrua
pointerintheCIR
– Thestoragestructureissometimescalledvirtualmethodtables(vtable)
– Methodcallscanberepresentedasoffsetsfromthebeginningofthevtable
SummaryofOOPs
 OOprogramminginvolvesthreefundamentalconcepts:ADTs,inheritance,dynamic
binding
 Majordesignissues:exclusivityofobjects,subclassesandsubtypes,typecheckingandpol
ymorphism,singleandmultipleinheritance,dynamicbinding,explicitandimplicitde-
allocationofobjects,andnestedclasses
 SmalltalkisapureOOL
 C++hastwodistincttypesystem(hybrid)
 JavaisnotahybridlanguagelikeC++;itsupportsonlyOOprogramming
 C#isbasedonC++andJava
 ImplementingOOPinvolvessomenewdatastructures

Concurrency
 Concurrencycanoccuratfourlevels:
– Machineinstructionlevel
– High-levellanguagestatementlevel
– Unitlevel
– Programlevel
 Becausetherearenolanguageissuesininstruction-andprogram-
levelconcurrency,theyarenotaddressedhere

64
MultiprocessorArchitectures
 Late1950s-onegeneral-
purposeprocessorandoneormorespecialpurposeprocessorsforinputandoutputopera
tions
 Early1960s-multiplecompleteprocessors,usedforprogram-levelconcurrency
 Mid-1960s-multiplepartialprocessors,usedforinstruction-levelconcurrency
 Single-InstructionMultiple-Data(SIMD)machines
 Multiple-InstructionMultiple-Data(MIMD)machines
– Independentprocessorsthatcanbesynchronized(unit-levelconcurrency)
CategoriesofConcurrency
 Athreadofcontrolinaprogramisthesequenceofprogrampointsreachedascontrolflowst
hroughtheprogram
 CategoriesofConcurrency:
– Physicalconcurrency-Multipleindependentprocessors(multiplethreadsofcontrol)
– Logicalconcurrency-Theappearanceofphysicalconcurrencyispresentedbytime-
sharingoneprocessor(softwarecanbedesignedasifthereweremultiplethreadsofco
ntrol)
 Coroutines(quasi-concurrency)haveasinglethreadofcontrol
MotivationsforStudyingConcurrency
 Involvesadifferentwayofdesigningsoftwarethatcanbeveryuseful—manyreal-
worldsituationsinvolveconcurrency
 Multiprocessorcomputerscapableofphysicalconcurrencyarenowwidelyused

Subprogram-LevelConcurrency
 Ataskorprocessisaprogramunitthatcanbeinconcurrentexecutionwithotherprogra
munits
 Tasksdifferfromordinarysubprogramsinthat:
– Ataskmaybeimplicitlystarted
– Whenaprogramunitstartstheexecutionofatask,itisnotnecessarilysuspended
– Whenatask‘sexecutioniscompleted,controlmaynotreturntothecaller
 Tasksusuallyworktogether
TwoGeneralCategoriesofTasks
 Heavyweighttasksexecuteintheirownaddressspace
 Lightweighttasksallruninthesameaddressspace
 Ataskisdisjointifitdoesnotcommunicatewithoraffecttheexecutionofanyothertaskinth
eprograminanyway
TaskSynchronization
 Amechanismthatcontrolstheorderinwhichtasksexecute
 Twokindsofsynchronization
– Cooperationsynchronization
– Competitionsynchronization
 Taskcommunicationisnecessaryforsynchronization,providedby:
– Sharednonlocalvariables
– Parameters
– Messagepassing
Kindsofsynchronization
 Cooperation:TaskAmustwaitfortaskBtocompletesomespecificactivitybeforetaskAca
ncontinueitsexecution,e.g.,theproducer-consumerproblem

65
 Competition:Twoormoretasksmustusesomeresourcethatcannotbesimultaneousl
yused,e.g.,asharedcounter
– Competitionisusuallyprovidedbymutuallyexclusiveaccess(approachesarediscuss
edlater)

Figure6.1NeedforCompetitionSynchronization
Scheduler
 Providingsynchronizationrequiresamechanismfordelayingtaskexecution
 Taskexecutioncontrolismaintainedbyaprogramcalledthescheduler,whichmapsta
skexecutionontoavailableprocessors
TaskExecutionStates
 New-createdbutnotyetstarted
 Ready-readytorunbutnotcurrentlyrunning(noavailableprocessor)
 Running
 Blocked-
hasbeenrunning,butcannotnowcontinue(usuallywaitingforsomeeventtooccur)
 Dead-nolongeractiveinanysense
LivenessandDeadlock
 Livenessisacharacteristicthataprogramunitmayormaynothave
– Insequentialcode,itmeanstheunitwilleventuallycompleteitsexecution
 Inaconcurrentenvironment,ataskcaneasilyloseitsliveness
 Ifalltasksinaconcurrentenvironmentlosetheirliveness,itiscalleddeadlock
DesignIssuesforConcurrency
 Competitionandcooperationsynchronization
 Controllingtaskscheduling
 Howandwhentasksstartandendexecution
 Howandwhenaretaskscreated
MethodsofProvidingSynchronization
 Semaphores
 Monitors
 MessagePassing

Semaphores
 Dijkstra-1965
 Asemaphoreisadatastructureconsistingofacounterandaqueueforstoringtaskdesc
riptors
 Semaphorescanbeusedtoimplementguardsonthecodethataccessesshareddatastr
uctures
 Semaphoreshaveonlytwooperations,waitandrelease(originallycalledPand
VbyDijkstra)

66
 Semaphores can be used to provide both competition and
cooperationsynchronization
CooperationSynchronizationwithSemaphores
 Example:Asharedbuffer
 ThebufferisimplementedasanADTwiththeoperationsDEPOSITandFETCHastheonlyw
aystoaccessthebuffer
 Usetwosemaphoresforcooperation:emptyspotsandfullspots
 Thesemaphorecountersareusedtostorethenumbersofemptyspotsandfullspotsintheb
uffer
 DEPOSITmustfirstcheckemptyspotstoseeifthereisroominthebuffer
 Ifthereisroom,thecounterofemptyspotsisdecrementedandthevalueisinserted
 Ifthereisnoroom,thecallerisstoredinthequeueofemptyspots
 WhenDEPOSITisfinished,itmustincrementthecounteroffullspots
 FETCHmustfirstcheckfullspotstoseeifthereisavalue
– Ifthereisafullspot,thecounteroffullspotsisdecrementedandthevalueisremoved
– Iftherearenovaluesinthebuffer,thecallermustbeplacedinthequeueoffullspots
– WhenFETCHisfinished,itincrementsthecounterofemptyspots
 TheoperationsofFETCHandDEPOSITonthesemaphoresareaccomplishedthrought
wosemaphoreoperationsnamedwaitandrelease

Semaphores:WaitOperation
wait(aSemaphore)
ifaSemaphore‘scounter>0thendecrement
aSemaphore‘scounter
else
putthecallerinaSemaphore‘squeueattemp
ttotransfercontroltoareadytask
--ifthetaskreadyqueueisempty,
--deadlockoccurs
end

Semaphores:ReleaseOperation
release(aSemaphore)
ifaSemaphore‘squeueisemptythenincrementa
Semaphore‘scounter
else
putthecallingtaskinthetaskreadyqueuetransfercont
roltoataskfromaSemaphore‘squeue
end

ProducerConsumerCode
semaphorefullspots,emptyspots;fullst
ops.count=0;emptyspots.coun
t=BUFLEN;taskproducer;
loop
--produceVALUE–-
wait(emptyspots);{waitforspace}DEPO
SIT(VALUE);
release(fullspots);{increasefilled}e
ndloop;
endproducer;

67
ProducerConsumerCode
taskconsumer;
loop
wait(fullspots);{waittillnotempty}}FET
CH(VALUE);
release(emptyspots);{increaseempty}
--consumeVALUE–-
endloop;
endconsumer;
CompetitionSynchronizationwithSemaphores
 Athirdsemaphore,namedaccess,isusedtocontrolaccess(competitionsynchronization)
– Thecounterofaccesswillonlyhavethevalues0and1
– Suchasemaphoreiscalledabinarysemaphore
 Notethatwaitandreleasemustbeatomic!
ProducerConsumerCode
semaphoreaccess,fullspots,emptyspots;access.count
=0;
fullstops.count=0;emptyspots.
count=BUFLEN;taskproducer;
loop
--produceVALUE–-
wait(emptyspots);{waitforspace}wait(
access);{waitforaccess)DEPOSIT(VAL
UE);
release(access);{relinquishaccess}relea
se(fullspots);{increasefilled}
endloop;
endproducer;

ProducerConsumerCode
taskconsumer;
loop
wait(fullspots);{waittillnotempty}wait(
access);{waitforaccess}FETCH(VALUE);
release(access);{relinquishaccess}rele
ase(emptyspots);{increaseempty}
--consumeVALUE–-
endloop;
endconsumer;
EvaluationofSemaphores
 Misuseofsemaphorescancausefailuresincooperationsynchronization,
e.g.,thebufferwilloverflowifthewaitoffullspotsisleftout
 Misuseofsemaphorescancausefailuresincompetitionsynchronization,
e.g.,theprogramwilldeadlockifthereleaseofaccessisleftout

Monitors
 Ada,Java,C#
 Theidea:encapsulatetheshareddataanditsoperationstorestrictaccess
 Amonitorisanabstractdatatypeforshareddata
CompetitionSynchronization
 Shareddataisresidentinthemonitor(ratherthanintheclientunits)
 Allaccessresidentinthemonitor

68
– Monitorimplementationguaranteesynchronizedaccessbyallowingonlyoneaccessa
tatime
– Callstomonitorproceduresareimplicitlyqueuedifthemonitorisbusyatthetimeofthe
call
CooperationSynchronization
 Cooperationbetweenprocessesisstillaprogrammingtask
– Programmermustguaranteethatasharedbufferdoesnotexperienceunderfloworov
erflow

Figure6.2CooperationSynchronization
EvaluationofMonitors
 Abetterwaytoprovidecompetitionsynchronizationthanaresemaphores
 Semaphorescanbeusedtoimplementmonitors
 Monitorscanbeusedtoimplementsemaphores
 Supportforcooperationsynchronizationisverysimilaraswithsemaphores,soithast
hesameproblems

MessagePassing
 Messagepassingisageneralmodelforconcurrency
– Itcanmodelbothsemaphoresandmonitors
– Itisnotjustforcompetitionsynchronization
 Centralidea:taskcommunicationislikeseeingadoctor--
mostofthetimeshewaitsforyouoryouwaitforher,butwhenyouarebothready,yougetto
gether,orrendezvous
MessagePassingRendezvous
 Tosupportconcurrenttaskswithmessagepassing,alanguageneeds:
– Amechanismtoallowatasktoindicatewhenitiswillingtoacceptmessages
– Awaytorememberwhoiswaitingtohaveitsmessageacceptedandsome
“fair”wayofchoosingthenextmessage
 Whenasendertask‘smessageisacceptedbyareceivertask,theactualmessagetransm
issioniscalledarendezvous

AdaSupportforConcurrency
 TheAda83Message-PassingModel
– Adataskshavespecificationandbodyparts,likepackages;thespechastheinterfac
e,whichisthecollectionofentrypoints:
taskTask_Exampleis
entryENTRY_1(Item:inInteger);endT
ask_Example;

69
TaskBody
 Thebodytaskdescribestheactionthattakesplacewhenarendezvousoccurs
 Ataskthatsendsamessageissuspendedwhilewaitingforthemessagetobeacceptedandd
uringtherendezvous
 Entrypointsinthespecaredescribedwithacceptclausesinthebodyaccept
entry_name(formalparameters)do

endentry_name

ExampleofaTaskBody
taskbodyTask_Exampleisbegi
n
loop
acceptEntry_1(Item:inFloat)do
...
endEntry_1;
endloop;en
dTask_Example;

AdaMessagePassingSemantics
 Thetaskexecutestothetopoftheacceptclauseandwaitsforamessage
 Duringexecutionoftheacceptclause,thesenderissuspended
 acceptparameterscantransmitinformationineitherorbothdirections
 Everyacceptclausehasanassociatedqueuetostorewaitingmessages

Figure6.3RendezvousTimeLines

MessagePassing:Server/ActorTasks
 Ataskthathasacceptclauses,butnoothercodeiscalledaservertask(theexampleabov
eisaservertask)
 Ataskwithoutacceptclausesiscalledanactortask
– Anactortaskcansendmessagestoothertasks
– Note:Asendermustknowtheentrynameofthereceiver,butnotviceversa(asymmetri
c)

70
Figure6.4GraphicalRepresentationofaRendezvous

Example:ActorTask
taskWater_Monitor;--specificationtaskbodybodyWater_Monitoris--bodybegin
loop
ifWater_Level>Max_Levelthe
nSound_Alarm;
endif;
delay1.0;--Nofurtherexecution
--foratleast1second
endloop;end
Water_Monitor;
MultipleEntryPoints
 Taskscanhavemorethanoneentrypoint
– Thespecificationtaskhasanentryclauseforeach
– Thetaskbodyhasanacceptclauseforeachentryclause,placedinaselectclause,whi
chisinaloop
ATaskwithMultipleEntries
taskbodyTellerisloop
select
acceptDrive_Up(formalparams)do
...
endDrive_Up;
...
or
acceptWalk_Up(formalparams)do
...
endWalk_Up;
...
endselect;en
dloop;
endTeller;

SemanticsofTaskswithMultipleacceptClauses
 Ifexactlyoneentryqueueisnonempty,chooseamessagefromit
 Ifmorethanoneentryqueueisnonempty,chooseone,nondeterministically,fromwhi
chtoacceptamessage
 Ifallareempty,wait
 Theconstructisoftencalledaselectivewait
 Extendedacceptclause-codefollowingtheclause,butbeforethenextclause
– Executedconcurrentlywiththecaller

71
CooperationSynchronizationwithMessagePassing
 ProvidedbyGuardedacceptclauses
whennotFull(Buffer)=>acceptD
eposit(New_Value)do
 Anacceptclausewithawithawhenclauseiseitheropenorclosed
– Aclausewhoseguardistrueiscalledopen
– Aclausewhoseguardisfalseiscalledclosed
– Aclausewithoutaguardisalwaysopen

SemanticsofselectwithGuardedacceptClauses:
 selectfirstcheckstheguardsonallclauses
 Ifexactlyoneisopen,itsqueueischeckedformessages
 Ifmorethanoneareopen,non-
deterministicallychooseaqueueamongthemtocheckformessages
 Ifallareclosed,itisaruntimeerror
 Aselectclausecanincludeanelseclausetoavoidtheerror
– Whentheelseclausecompletes,thelooprepeats

ExampleofaTaskwithGuardedacceptClauses
 Note:Thestationmaybeoutofgasandtheremayormaynotbeapositionavailableinthegar
age
taskGas_Station_Attendantis
entryService_Island(Car:Car_Type);entr
yGarage(Car:Car_Type);
endGas_Station_Attendant;

ExampleofaTaskwithGuardedacceptClauses
taskbodyGas_Station_Attendantisbegi
n
loop
select
whenGas_Available=>
acceptService_Island(Car:Car_Type)doFill_With_Gas(C
ar);
endService_Island;or
whenGarage_Available=>
acceptGarage(Car:Car_Type)doFix(C
ar);
endGarage;else
Sleep;
endselect;
endloop;
endGas_Station_Attendant;
CompetitionSynchronizationwithMessagePassing
 Modelingmutuallyexclusiveaccesstoshareddata
 Example--asharedbuffer
 Encapsulatethebufferanditsoperationsinatask
 Competitionsynchronizationisimplicitinthesemanticsofacceptclauses
– Onlyoneacceptclauseinataskcanbeactiveatanygiventime

72
TaskTermination
 Theexecutionofataskiscompletedifcontrolhasreachedtheendofitscodebody
 Ifataskhascreatednodependenttasksandiscompleted,itisterminated
 Ifataskhascreateddependenttasksandiscompleted,itisnotterminateduntilallitsdepen
denttasksareterminated
TheterminateClause
 Aterminateclauseinaselectisjustaterminatestatement
 Aterminateclauseisselectedwhennoacceptclauseisopen
 Whenaterminateisselectedinatask,thetaskisterminatedonlywhenitsmasterandalloft
hedependentsofitsmasterareeithercompletedorarewaitingataterminate
 Ablockorsubprogramisnotleftuntilallofitsdependenttasksareterminated
MessagePassingPriorities
 ThepriorityofanytaskcanbesetwiththepragmaprioritypragmaPriority(expression);
 Thepriorityofataskappliestoitonlywhenitisinthetaskreadyqueue

BinarySemaphores
 ForsituationswherethedatatowhichaccessistobecontrolledisNOTencapsulatedin
atask
taskBinary_Semaphoreisent
ryWait;
entryrelease;end
Binary_Semaphore;
taskbodyBinary_Semaphoreisbegin
loop
acceptWait;acce
ptRelease;endloo
p;
endBinary_Semaphore;

ConcurrencyinAda95
 Ada95includesAda83featuresforconcurrency,plustwonewfeatures
– Protectedobjects:Amoreefficientwayofimplementingshareddatatoallowaccesstoash
areddatastructuretobedonewithoutrendezvous
– Asynchronouscommunication

Ada95:ProtectedObjects
 Aprotectedobjectissimilartoanabstractdatatype
 Accesstoaprotectedobjectiseitherthroughmessagespassedtoentries,aswithatask,
orthroughprotectedsubprograms
 A protected procedure provides mutually exclusive read-write access
toprotectedobjects
 Aprotectedfunctionprovidesconcurrentread-onlyaccesstoprotectedobjects

AsynchronousCommunication
 Providedthroughasynchronousselectstructures
 Anasynchronousselecthastwotriggeringalternatives,anentryclauseoradelay
– Theentryclauseistriggeredwhensentamessage
– Thedelayclauseistriggeredwhenitstimelimitisreached

73
EvaluationoftheAda
 Messagepassingmodelofconcurrencyispowerfulandgeneral
 Protectedobjectsareabetterwaytoprovidesynchronizedshareddata
 Intheabsenceofdistributedprocessors,thechoicebetweenmonitorsandtaskswithmess
agepassingissomewhatamatteroftaste
 Fordistributedsystems,messagepassingisabettermodelforconcurrency

JavaThreads
 TheconcurrentunitsinJavaaremethodsnamedrun
– Arunmethodcodecanbeinconcurrentexecutionwithothersuchmethods
– Theprocessinwhichtherunmethodsexecuteiscalledathread
ClassmyThreadextendsThread{
publicvoidrun(){…}
}

ThreadmyTh=newMyThread();myTh.st
art();

ControllingThreadExecution
 TheThreadclasshasseveralmethodstocontroltheexecutionofthreads
– Theyieldisarequestfromtherunningthreadtovoluntarilysurrendertheprocessor
– Thesleepmethodcanbeusedbythecallerofthemethodtoblockthethread
– Thejoinmethodisusedtoforceamethodtodelayitsexecutionuntiltherunmethodofa
notherthreadhascompleteditsexecution

ThreadPriorities
 Athread‘sdefaultpriorityisthesameasthethreadthatcreateit
– Ifmaincreatesathread,itsdefaultpriorityisNORM_PRIORITY
 Threads defined two other priority constants, MAX_PRIORITY
andMIN_PRIORITY
 ThepriorityofathreadcanbechangedwiththemethodssetPriority

CompetitionSynchronizationwithJavaThreads
 Amethodthatincludesthesynchronizedmodifierdisallowsanyothermethodfromrunni
ngontheobjectwhileitisinexecution

public synchronized void deposit( int i) {…}
public synchronized int fetch() {…}

 Theabovetwomethodsaresynchronizedwhichpreventsthemfrominterferingwitheac
hother
 Ifonlyapartofamethodmustberunwithoutinterference,itcanbesynchronizedthroughs
ynchronizedstatement
synchronized(expression)
statement
CooperationSynchronizationwithJavaThreads
 CooperationsynchronizationinJavaisachievedviawait,notify,andnotifyAllmethod
s
– AllmethodsaredefinedinObject,whichistherootclassinJava,soallobjectsinheritthe
m
 Thewaitmethodmustbecalledinaloop

74
 Thenotifymethodiscalledtotellonewaitingthreadthattheeventitwaswaitinghashappe
ned
 ThenotifyAllmethodawakensallofthethreadsontheobject‘swaitlist

Java’sThreadEvaluation
 Java‘ssupportforconcurrencyisrelativelysimplebuteffective
 NotaspowerfulasAda‘stasks

C#Threads
 LooselybasedonJavabuttherearesignificantdifferences
 Basicthreadoperations
– Anymethodcanruninitsownthread
– AthreadiscreatedbycreatingaThreadobject
– Creatingathreaddoesnotstartitsconcurrentexecution;itmustberequestedthro
ughtheStartmethod
– AthreadcanbemadetowaitforanotherthreadtofinishwithJoin
– AthreadcanbesuspendedwithSleep
– AthreadcanbeterminatedwithAbort

SynchronizingThreads
 ThreewaystosynchronizeC#threads
– TheInterlockedclass
 Usedwhentheonlyoperationsthatneedtobesynchronizedareincrementingordecreme
ntingofaninteger
– Thelockstatement
 Usedtomarkacriticalsectionofcodeinathreadlock(expression){…}
– TheMonitorclass
 Provides four methods that can be used to provide more
sophisticatedsynchronization
C#’sConcurrencyEvaluation
 AnadvanceoverJavathreads,e.g.,anymethodcanrunitsownthread
 ThreadterminationiscleanerthaninJava
 Synchronizationismoresophisticated

Statement-LevelConcurrency
 Objective:Provideamechanismthattheprogrammercanusetoinformcompilerofwaysit
canmaptheprogramontomultiprocessorarchitecture
 Minimizecommunicationamongprocessorsandthememoriesoftheotherprocessor
s
High-PerformanceFortran
 Acollectionofextensionsthatallowtheprogrammertoprovideinformationtothecompil
ertohelpitoptimizecodeformultiprocessorcomputers
 Specifythenumberofprocessors,thedistributionofdataoverthememoriesofthoseproc
essors,andthealignmentofdata
PrimaryHPFSpecifications
 Numberofprocessors
!HPF$PROCESSORSprocs(n)
 Distributionofdata
!HPF$DISTRIBUTE(kind)ONTOprocs::identifier_list
– kindcanbeBLOCK(distributedatatoprocessorsinblocks)orCYCLIC(
distributedatatoprocessorsoneelementatatime)
75
 Relatethedistributionofonearraywiththatofanother
ALIGNarray1_elementWITHarray2_element
Statement-
LevelConcurrencyExampleRE
ALlist_1(1000),list_2(1000)INTEGERlis
t_3(500),list_4(501)
!HPF$PROCESSORSproc(10)
!HPF$DISTRIBUTE(BLOCK)ONTOprocs::
list_1,list_2
!HPF$ALIGNlist_1(index)WITHlist_4
(index+1)

list_1(index)=list_2(index)list_3(i
ndex)=list_4(index+1)
 FORALLstatementisusedtospecifyalistofstatementsthatmaybeexecutedconcurrently
FORALL(index=1:1000)
list_1(index)=list_2(index)
 Specifiesthatall1,000RHSsoftheassignmentscanbeevaluatedbeforeanyassignmen
ttakesplace

Summary
 Concurrentexecutioncanbeattheinstruction,statement,orsubprogramlevel
 Physicalconcurrency:whenmultipleprocessorsareusedtoexecuteconcurrentunits
 Logicalconcurrency:concurrentunitedareexecutedonasingleprocessor
 Two primary facilities to support subprogram concurrency:
competitionsynchronizationandcooperationsynchronization
 Mechanisms:semaphores,monitors,rendezvous,threads
 High-
PerformanceFortranprovidesstatementsforspecifyinghowdataistobedistributedove
rthememoryunitsconnectedtomultipleprocessors

76
ExceptionHandling&LogicProgrammingLanguage

IntroductiontoExceptionHandling
 Inalanguagewithoutexceptionhandling
– Whenanexceptionoccurs,controlgoestotheoperatingsystem,whereamessageisdis
playedandtheprogramisterminated
 Inalanguagewithexceptionhandling
– Programsareallowedtotrapsomeexceptions,therebyprovidingthepossibilityoffixi
ngtheproblemandcontinuing
BasicConcepts–CO3
 Manylanguagesallowprogramstotrapinput/outputerrors(includingEOF)
 Anexceptionisanyunusualevent,eithererroneousornot,detectablebyeitherhardwareo
rsoftware,thatmayrequirespecialprocessing
 Thespecialprocessingthatmayberequiredafterdetectionofanexceptioniscalledexcepti
onhandling
 Theexceptionhandlingcodeunitiscalledanexceptionhandler

ExceptionHandlingAlternatives
 Anexceptionisraisedwhenitsassociatedeventoccurs
 Alanguagethatdoesnothaveexceptionhandlingcapabilitiescanstilldefine,detect,ra
ise,andhandleexceptions(userdefined,softwaredetected)
 Alternatives:
– Sendanauxiliaryparameterorusethereturnvaluetoindicatethereturnstatusofasub
program
– Passanexceptionhandlingsubprogramtoallsubprograms

AdvantagesofBuilt-inExceptionHandling
 Errordetectioncodeistedioustowriteanditclutterstheprogram
 Exception handling encourages programmers to consider many
differentpossibleerrors
 Exceptionpropagationallowsahighlevelofreuseofexceptionhandlingcode

DesignIssues
 Howareuser-definedexceptionsspecified?
 Shouldtherebedefaultexceptionhandlersforprogramsthatdonotprovidetheirown?
 Canbuilt-inexceptionsbeexplicitlyraised?
 Arehardware-detectableerrorstreatedasexceptionsthatcanbehandled?
 Arethereanybuilt-inexceptions?
 Howcanexceptionsbedisabled,ifatall?
 Howandwhereexceptionhandlersspecifiedandwhataretheirscope?
 Howisanexceptionoccurrenceboundtoanexceptionhandler?
 Caninformationabouttheexceptionbepassedtothehandler?
 Wheredoesexecutioncontinue,ifatall,afteranexceptionhandlercompletesitsexecution
?(continuationvs.resumption)
 Issomeformoffinalizationprovided?

77
Figure7.1ExceptionHandlingControlFlow

ExceptionHandlinginAda–CO3
 TheframeofanexceptionhandlerinAdaiseitherasubprogrambody,apackagebody,a
task,orablock
 Becauseexceptionhandlersareusuallylocaltothecodeinwhichtheexceptioncanberaise
d,theydonothaveparameters
AdaExceptionHandlers
 Handlerform:
whenexception_choice{|exception_choice}=>statement_sequence
...
[whenothers=>statement_sequ
ence]
exception_choiceform:excep
tion_name|others
 Handlersareplacedattheendoftheblockorunitinwhichtheyoccur
BindingExceptionstoHandlers
 Iftheblockorunitinwhichanexceptionisraiseddoesnothaveahandlerforthatexception,
theexceptionispropagatedelsewheretobehandled
– Procedures-propagateittothecaller
– Blocks-propagateittothescopeinwhichitappears
– Packagebody-
propagateittothedeclarationpartoftheunitthatdeclaredthepackage(ifitisalibraryu
nit,theprogramisterminated)
– Task-nopropagation;ifithasahandler,executeit;ineithercase,markit"completed"
Continuation
 Theblockorunitthatraisesanexceptionbutdoesnothandleitisalwaysterminated(alsoa
nyblockorunittowhichitispropagatedthatdoesnothandleit)
OtherDesignChoices
 User-definedExceptionsform:
exception_name_list:exception;
 RaisingExceptionsform:
raise[exception_name]
– (theexceptionnameisnotrequiredifitisinahandler--
inthiscase,itpropagatesthesameexception)
 Exceptionconditionscanbedisabledwith:
pragmaSUPPRESS(exception_list)
PredefinedExceptions
 CONSTRAINT_ERROR-indexconstraints,rangeconstraints,etc.
 NUMERIC_ERROR-
numericoperationcannotreturnacorrectvalue(overflow,divisionbyzero,etc.)

78
 PROGRAM_ERROR-calltoasubprogramwhosebodyhasnotbeenelaborated
 STORAGE_ERROR-systemrunsoutofheap
 TASKING_ERROR-anerrorassociatedwithtasks
Evaluation
 TheAdadesignforexceptionhandlingembodiesthestate-of-the-
artinlanguagedesignin1980
 AsignificantadvanceoverPL/I
 AdawastheonlywidelyusedlanguagewithexceptionhandlinguntilitwasaddedtoC++

ExceptionHandlinginC++-CO3
 AddedtoC++in1990
 DesignisbasedonthatofCLU,Ada,andML
C++ExceptionHandlers
 ExceptionHandlersForm:
try{
--codethatisexpectedtoraiseanexception
}
catch(formalparameter){
--handlercode
}
...
catch(formalparameter){
--handlercode
}
ThecatchFunction
 catchisthenameofallhandlers--
itisanoverloadedname,sotheformalparameterofeachmustbeunique
 Theformalparameterneednothaveavariable
– Itcanbesimplyatypenametodistinguishthehandleritisinfromothers
 Theformalparametercanbeusedtotransferinformationtothehandler
 Theformalparametercanbeanellipsis,inwhichcaseithandlesallexceptionsnotyeth
andled

ThrowingExceptions
 Exceptionsareallraisedexplicitlybythestatement:throw[expression];
 Thebracketsaremetasymbols
 Athrowwithoutanoperandcanonlyappearinahandler;whenitappears,itsimplyre-
raisestheexception,whichisthenhandledelsewhere
 Thetypeoftheexpressiondisambiguatestheintendedhandler

UnhandledExceptions
 Anunhandledexceptionispropagatedtothecallerofthefunctioninwhichitisraised
 Thispropagationcontinuestothemainfunction

Continuation
 Afterahandlercompletesitsexecution,controlflowstothefirststatementafterthelastha
ndlerinthesequenceofhandlersofwhichitisanelement
 Otherdesignchoices

79
– Allexceptionsareuser-defined
– Exceptionsareneitherspecifiednordeclared
– Functionscanlisttheexceptionstheymayraise
– Withoutaspecification,afunctioncanraiseanyexception(thethrowclause)
Evaluation
 Itisoddthatexceptionsarenotnamedandthathardware-andsystemsoftware-
detectableexceptionscannotbehandled
 Bindingexceptionstohandlersthroughthetypeoftheparametercertainlydoesnotprom
otereadability

ExceptionHandlinginJava–CO3
 BasedonthatofC++,butmoreinlinewithOOPphilosophy
 AllexceptionsareobjectsofclassesthataredescendantsoftheThrowableclass
ClassesofExceptions
 TheJavalibraryincludestwosubclassesofThrowable:
– Error
o ThrownbytheJavainterpreterforeventssuchasheapoverflow
o Neverhandledbyuserprograms
– Exception
o User-definedexceptionsareusuallysubclassesofthis
o Hastwopredefinedsubclasses,IOExceptionandRuntimeException
e.g.,ArrayIndexOutOfBoundsExceptionandNullPointerException
JavaExceptionHandlers
 LikethoseofC++,excepteverycatchrequiresanamedparameterandallparametersmust
bedescendantsofThrowable
 SyntaxoftryclauseisexactlythatofC++
 Exceptionsarethrownwiththrow,asinC++,butoftenthethrowincludesthenewoperator
tocreatetheobject,asin:thrownewMyException();
BindingExceptionstoHandlers
 BindinganexceptiontoahandlerissimplerinJavathanitisinC++
– Anexceptionisboundtothefirsthandlerwithaparameteristhesameclassasthethrow
nobjectoranancestorofit
 Anexceptioncanbehandledandrethrownbyincludingathrowinthehandler(ahandlerco
uldalsothrowadifferentexception)
Continuation
 Ifnohandlerisfoundinthemethod,theexceptionispropagatedtothemethod‘scaller
 Ifnohandlerisfound(allthewaytomain),theprogramisterminated
 Toensurethatallexceptionsarecaught,ahandlercanbeincludedinanytryconstructt
hatcatchesallexceptions
– SimplyuseanExceptionclassparameter
– Ofcourse,itmustbethelastinthetryconstruct
CheckedandUncheckedExceptions
 TheJavathrowsclauseisquitedifferentfromthethrowclauseofC++
 ExceptionsofclassErrorandRunTimeExceptionandalloftheirdescendantsarecalle
duncheckedexceptions;allotherexceptionsarecalledcheckedexceptions
 Checkedexceptionsthatmaybethrownbyamethodmustbeeither:
– Listedinthethrowsclause,or
– Handledinthemethod

80
OtherDesignChoices
 Amethodcannotdeclaremoreexceptionsinitsthrowsclausethanthemethoditoverrides
 Amethodthatcallsamethodthatlistsaparticularcheckedexceptioninitsthrowsclauseha
sthreealternativesfordealingwiththatexception:
– Catchandhandletheexception
– Catchtheexceptionandthrowanexceptionthatislistedinitsownthrowsclause
– Declareitinitsthrowsclauseanddonothandleit
ThefinallyClause
 Canappearattheendofatryconstruct
 Form:
finally{..}
 Purpose:Tospecifycodethatistobeexecuted,regardlessofwhathappensinthetryconstr
uct
Example
 Atryconstructwithafinallyclausecanbeusedoutsideexceptionhandling
try{
for(index=0;index<100;index++){

if(…){
return;
}//**endofif
}//**endoftryclausefinally{

}//**endoftryconstruct
Assertions
 Statementsintheprogramdeclaringabooleanexpressionregardingthecurrentstate
ofthecomputation
 Whenevaluatedtotruenothinghappens
 WhenevaluatedtofalseanAssertionErrorexceptionisthrown
 Canbedisabledduringruntimewithoutprogrammodificationorrecompilation
 Twoforms
– assertcondition;
– assertcondition:expression;
Evaluation
 ThetypesofexceptionsmakesmoresensethaninthecaseofC++
 ThethrowsclauseisbetterthanthatofC++(ThethrowclauseinC++sayslittletotheprogra
mmer)
 Thefinallyclauseisoftenuseful
 TheJavainterpreterthrowsavarietyofexceptionsthatcanbehandledbyuserprograms
SummaryofExceptionHandling
 Adaprovidesextensiveexception-handlingfacilitieswithacomprehensivesetofbuilt-
inexceptions.
 C++includesnopredefinedexceptions.Exceptionsareboundtohandlersbyconnectingt
hetypeofexpressioninthethrowstatementtothatoftheformalparameterofthecatchfun
ction
 JavaexceptionsaresimilartoC++exceptionsexceptthataJavaexceptionmustbeades
cendantoftheThrowableclass.AdditionallyJavaincludesafinallyclause

81
LogicProgrammingIntroductionCO4
 Logic programming languages, sometimes called declarative
programminglanguages
 Expressprogramsinaformofsymboliclogic
 Usealogicalinferencingprocesstoproduceresults
 Declarativeratherthatprocedural:
– Onlyspecificationofresultsarestated(notdetailedproceduresforproducingthem)
Proposition
 Alogicalstatementthatmayormaynotbetrue
– Consistsofobjectsandrelationshipsofobjectstoeachother

SymbolicLogic
 Logicwhichcanbeusedforthebasicneedsofformallogic:
– Expresspropositions
– Expressrelationshipsbetweenpropositions
– Describehownewpropositionscanbeinferredfromotherpropositions
 Particularformofsymboliclogicusedforlogicprogrammingcalledpredicatecalculus

ObjectRepresentation
 Objectsinpropositionsarerepresentedbysimpleterms:eitherconstantsorvariables
 Constant:asymbolthatrepresentsanobject
 Variable:asymbolthatcanrepresentdifferentobjectsatdifferenttimes
– Differentfromvariablesinimperativelanguages

CompoundTerms
 Atomicpropositionsconsistofcompoundterms
 Compoundterm:oneelementofamathematicalrelation,writtenlikeamathematicalf
unction
– Mathematicalfunctionisamapping
– Canbewrittenasatable

PartsofaCompoundTerm
 Compoundtermcomposedoftwoparts
– Functor:functionsymbolthatnamestherelationship
– Orderedlistofparameters(tuple)
 Examples:
student(jon)like(set
h,OSX)like(nick,win
dows)like(jim,linux)

FormsofaProposition
 Propositionscanbestatedintwoforms:
– Fact:propositionisassumedtobetrue
– Query:truthofpropositionistobedetermined
 Compoundproposition:
– Havetwoormoreatomicpropositions
– Propositionsareconnectedbyoperators

82
LogicalOperators
Name Symbol Example Meaning
Negation  a anotb
Conjunction  ab aandb
Disjunction  ab aorb
Equivalence  ab aisequivalenttob
 aba aimpliesb
Implication
 b bimpliesa

Quantifiers
Name Example Meaning
universal X.P ForallX,Pistrue
existential X.P ThereexistsavalueofXsuchthatPistrue

ClausalForm
 Toomanywaystostatethesamething
 Useastandardformforpropositions
 Clausalform:
– B1B2…BnA1A2…Am
– meansifalltheAsaretrue,thenatleastoneBistrue
 Antecedent:rightside
 Consequent:leftside
PredicateCalculusandProvingTheorems
 Auseofpropositionsistodiscovernewtheoremsthatcanbeinferredfromknownaxiomsa
ndtheorems
 Resolution:aninferenceprinciplethatallowsinferredpropositionstobecomputedfromg
ivenpropositions
Resolution
 Unification:findingvaluesforvariablesinpropositionsthatallowsmatchingprocesstosu
cceed
 Instantiation:assigningtemporaryvaluestovariablestoallowunificationtosucceed
 Afterinstantiatingavariablewithavalue,ifmatchingfails,mayneedto
backtrackandinstantiatewithadifferentvalue

TheoremProving
 Basisforlogicprogramming
 Whenpropositionsusedforresolution,onlyrestrictedformcanbeused
 Hornclause-canhaveonlytwoforms
– Headed:singleatomicpropositiononleftside
– Headless:emptyleftside(usedtostatefacts)
 MostpropositionscanbestatedasHornclauses

AnOverviewofLogicProgramming
 Declarativesemantics
– Thereisasimplewaytodeterminethemeaningofeachstatement
– Simplerthanthesemanticsofimperativelanguages
 Programmingisnonprocedural
– Programsdonotstatenowaresultistobecomputed,butrathertheformoftheresult

83
TheOriginsofProlog
 UniversityofAix-Marseille
– Naturallanguageprocessing
 UniversityofEdinburgh
– Automatedtheoremproving

TheBasicElementsofProLogCO4
 EdinburghSyntax
 Term:aconstant,variable,orstructure
 Constant:anatomoraninteger
 Atom:symbolicvalueofProlog
 Atomconsistsofeither:
– astringofletters,digits,andunderscoresbeginningwithalowercaseletter
– astringofprintableASCIIcharactersdelimitedbyapostrophes
Terms:VariablesandStructures
 Variable:anystringofletters,digits,andunderscoresbeginningwithanuppercaselett
er
 Instantiation:bindingofavariabletoavalue
– Lastsonlyaslongasittakestosatisfyonecompletegoal
 Structure:representsatomicproposition
functor(parameterlist)
FactStatements
 Usedforthehypotheses
 HeadlessHornclauses
female(shelley).m
ale(bill).father(bi
ll,jake).
RuleStatements
 Usedforthehypotheses
 HeadedHornclause
 Rightside:antecedent(ifpart)
– Maybesingletermorconjunction
 Leftside:consequent(thenpart)
– Mustbesingleterm
 Conjunction:multipletermsseparatedbylogicalANDoperations(implied)
ExampleRules
ancestor(mary,shelley):-mother(mary,shelley).
 Canusevariables(universalobjects)togeneralizemeaning:
parent(X,Y):-mother(X,Y).
parent(X,Y):-father(X,Y).
grandparent(X,Z):-parent(X,Y),parent(Y,Z).
sibling(X,Y):-mother(M,X),mother(M,Y),
father(F,X),father(F,Y).
GoalStatements
 Fortheoremproving,theoremisinformofpropositionthatwewantsystemtoproveordis
prove– goalstatement
 SameformatasheadlessHorn
man(fred)
 Conjunctivepropositionsandpropositionswithvariablesalsolegalgoals
father(X,mike)
InferencingProcessofProlog
 Queriesarecalledgoals

84
 Ifagoalisacompoundproposition,eachofthefactsisasubgoal
 Toproveagoalistrue,mustfindachainofinferencerulesand/orfacts.ForgoalQ:
B:-A
C:-B

Q:-P
 Processofprovingasubgoalcalledmatching,satisfying,orresolution
Approaches
 Bottom-upresolution,forwardchaining
– Beginwithfactsandrulesofdatabaseandattempttofindsequencethatleadstogoal
– Workswellwithalargesetofpossiblycorrectanswers
 Top-downresolution,backwardchaining
– Beginwithgoalandattempttofindsequencethatleadstosetoffactsindatabase
– Workswellwithasmallsetofpossiblycorrectanswers
 Prologimplementationsusebackwardchaining
SubgoalStrategies
 Whengoalhasmorethanonesubgoal,canuseeither
– Depth-firstsearch:findacompleteproofforthefirstsubgoalbeforeworkingonothers
– Breadth-firstsearch:workonallsubgoalsinparallel
 Prologusesdepth-firstsearch
– Canbedonewithfewercomputerresources
Backtracking
 Withagoalwithmultiplesubgoals,iffailtoshowtruthofoneofsubgoals,reconsiderprevio
ussubgoaltofindanalternativesolution:backtracking
 Beginsearchwhereprevioussearchleftoff
 Cantakelotsoftimeandspacebecausemayfindallpossibleproofstoeverysubgoal
SimpleArithmetic
 Prologsupportsintegervariablesandintegerarithmetic
 isoperator:takesanarithmeticexpressionasrightoperandandvariableasleftoperand
AisB/17+C
 Notthesameasanassignmentstatement!
Example
speed(ford,100).speed(ch
evy,105).speed(dodge,95)
.speed(volvo,80).time(for
d,20).time(chevy,21).time
(dodge,24).time(volvo,24
).
distance(X,Y):- speed(X,Speed),
time(X,Time),
YisSpeed*Time.
Trace
• Built-instructurethatdisplaysinstantiationsateachstep
• Tracingmodelofexecution-fourevents:
– Call(beginningofattempttosatisfygoal)
– Exit(whenagoalhasbeensatisfied)

85
– Redo(whenbacktrackoccurs)
– Fail(whengoalfails)
Example
likes(jake,chocolate).likes(jake,apric
ots).likes(darcie,licorice).likes(darci
e,apricots).

trace.likes(jak
e,X),likes(darci
e,X).

ListStructures
 Otherbasicdatastructure(besidesatomicpropositionswehavealreadyseen):list
 Listisasequenceofanynumberofelements
 Elementscanbeatoms,atomicpropositions,orotherterms(includingotherlists)
[apple,prune,grape,kumquat][](e
mptylist)
[X|Y](headXandtailY)
AppendExample
append([],List,List).
append([Head|List_1],List_2,[Head|List_3]):-
append(List_1,List_2,List_3).
ReverseExample
reverse([],[]).
reverse([Head|Tail],List):-
reverse(Tail,Result),append(
Result,[Head],List).
DeficienciesofProlog
 Resolutionordercontrol
 Theclosed-worldassumption
 Thenegationproblem
 Intrinsiclimitations

ApplicationsofLogicProgramming–CO4
 Relationaldatabasemanagementsystems
 Expertsystems
 Naturallanguageprocessing
SummaryofLogicProgramming
 Symboliclogicprovidesbasisforlogicprogramming
 Logicprogramsshouldbenonprocedural
 Prologstatementsarefacts,rules,orgoals
 ResolutionistheprimaryactivityofaProloginterpreter
 Althoughthereareanumberofdrawbackswiththecurrentstateoflogicprogrammingith
asbeenusedinanumberofareas

86
UNIT-5
FunctionalProgrammingLanguages&ScriptingLanguage

FunctionalProgrammingLanguageIntroduction–CO5
 ThedesignoftheimperativelanguagesisbaseddirectlyonthevonNeumannarchitecture
– Efficiencyistheprimaryconcern,ratherthanthesuitabilityofthelanguageforsoftwar
edevelopment
 Thedesignofthefunctionallanguagesisbasedonmathematicalfunctions
– Asolidtheoreticalbasisthatisalsoclosertotheuser,butrelativelyunconcernedwithth
earchitectureofthemachinesonwhichprogramswillrun

MathematicalFunctions
 Amathematicalfunctionisamappingofmembersofoneset,calledthedomainset,toan
otherset,calledtherangeset
 Alambdaexpressionspecifiestheparameter(s)andthemappingofafunctioninthefoll
owingform
(x)x*x*x
forthefunctioncube(x)=x*x*x
LambdaExpressions
 Lambdaexpressionsdescribenamelessfunctions
 Lambdaexpressionsareappliedtoparameter(s)byplacingtheparameter(s)aftertheexp
ression
e.g.,((x)x*x*x)(2)whi
chevaluatesto8
FunctionalForms
 Ahigher-
orderfunction,orfunctionalform,isonethateithertakesfunctionsasparametersoryields
afunctionasitsresult,orboth
FunctionComposition
 Afunctionalformthattakestwofunctionsasparametersandyieldsafunctionwhosev
alueisthefirstactualparameterfunctionappliedtotheapplicationofthesecond
Form:hf°g
whichmeansh(x)f(g(x))
Forf(x)x+2andg(x)3*x,hf°gy
ields(3*x)+2
Apply-to-all
 Afunctionalformthattakesasinglefunctionasaparameterandyieldsalistofvaluesobtain
edbyapplyingthegivenfunctiontoeachelementofalistofparameters
Form:
Forh(x)x*x
(h,(2,3,4))yields(4,9,16)

FundamentalsofFunctionalProgrammingLanguages-CO5
 TheobjectiveofthedesignofaFPListomimicmathematicalfunctionstothegreatestex
tentpossible
 ThebasicprocessofcomputationisfundamentallydifferentinaFPLthaninanimperat
ivelanguage

87
– Inanimperativelanguage,operationsaredoneandtheresultsarestoredinvariablesfo
rlateruse
– Managementofvariablesisaconstantconcernandsourceofcomplexityforimperativ
eprogramming
 InanFPL,variablesarenotnecessary,asisthecaseinmathematics
ReferentialTransparency
 InanFPL,theevaluationofafunctionalwaysproducesthesameresultgiventhesamepara
meters

TheFirstFunctionalProgrammingLanguage:LISP–CO5

LISPDataTypesandStructures
 Dataobjecttypes:originallyonlyatomsandlists
 Listform:parenthesizedcollectionsofsublistsand/oratoms
e.g.,(AB(CD)E)
 Originally,LISPwasatypelesslanguage
 LISPlistsarestoredinternallyassingle-linkedlists
LISPInterpretation
 Lambdanotationisusedtospecifyfunctionsandfunctiondefinitions.Func
tionapplicationsanddatahavethesameform.
e.g.,Ifthelist(ABC)isinterpretedasdataitisasimplelistofthreeatoms,A,BandC
Ifitisinterpretedasafunctionapplication,itmeansthatthefunctionnamedAisappli
edtothetwoparameters,BandC
 ThefirstLISPinterpreterappearedonlyasademonstrationoftheuniversalityofthecomp
utationalcapabilitiesofthenotation

ML–CO5
 Astatic-scopedfunctionallanguagewithsyntaxthatisclosertoPascalthantoLISP
 Usestypedeclarations,butalsodoestypeinferencingtodeterminethetypesofundecla
redvariables
 Itisstronglytyped(whereasSchemeisessentiallytypeless)andhasnotypecoercions
 Includesexceptionhandlingandamodulefacilityforimplementingabstractdatatypes
 Includeslistsandlistoperations
MLSpecifics
 Functiondeclarationform:
funname(parameters)=body;
e.g.,funcube(x:int)=x*x*x;
– Thetypecouldbeattachedtoreturnvalue,asin
funcube(x):int=x*x*x;
– Withnotypespecified,itwoulddefaultto
int(thedefaultfornumericvalues)
– User-
definedoverloadedfunctionsarenotallowed,soifwewantedacubefunctionforrealpa
rameters,itwouldneedtohaveadifferentname
– TherearenotypecoercionsinML
 MLselection
ifexpressionthenthen_expression
elseelse_expression

88
wherethefirstexpressionmustevaluatetoaBooleanvalue
 Patternmatchingisusedtoallowafunctiontooperateondifferentparameterforms
funfact(0)=1
|fact(n:int):int=n*fact(n–1)
 Lists
Literallistsarespecifiedinbrackets[3,5,
7]
[]istheemptylist
CONSisthebinaryinfixoperator,::
4::[3,5,7],whichevaluatesto[4,3,5,7]CARistheu
naryoperatorhd
CDRistheunaryoperatortlfunl
ength([])=0
|length(h::t)=1+length(t);funa
ppend([],lis2)=lis2
|append(h::t,lis2)=h::append(t,lis2);
 Thevalstatementbindsanametoavalue(similartoDEFINEinScheme)valdist
ance=time*speed;
– AsisthecasewithDEFINE,valisnothinglikeanassignmentstatementinanimperat
ivelanguage

Haskell–CO5
 SimilartoML(syntax,staticscoped,stronglytyped,typeinferencing,patternmatchin
g)
 DifferentfromML(andmostotherfunctionallanguages)inthatitispurelyfunctional(
e.g.,novariables,noassignmentstatements,andnosideeffectsofanykind)
SyntaxdifferencesfromML
fact0=1
factn=n*fact(n– 1)fib0=1
fib1=1
fib(n+2)=fib(n+1)+fibn
FunctionDefinitionswithDifferentParameterRanges
factn
|n==0=1
|n>0=n*fact(n–1)

subn
|n<10=0
|n>100=2
|otherwise=1s
quarex=x*x
- Worksforanynumerictypeofx
Lists
 Listnotation:Putelementsinbrackets
e.g.,directions=["north","south","east","west"]
 Length:#
e.g.,#directionsis4
 Arithmeticserieswiththe..operator
e.g.,[2,4..10]is[2,4,6,8,10]
 Catenationiswith++
e.g.,[1,3]++[5,7]resultsin[1,3,5,7]

89
 CONS,CAR,CDRviathecolonoperator(asinProlog)
e.g.,1:[3,5,7]resultsin[1,3,5,7]
FactorialRevisited
product[]=1
product(a:x)=a*productxfactn=
product[1..n]
ListComprehension
 Setnotation
 Listofthesquaresofthefirst20positiveintegers:[n*n|n←[1..20]]
 Allofthefactorsofitsgivenparameter:
factorsn=[i|i←[1..ndiv2],
nmodi==0]
Quicksort
sort[]=[]sort
(a:x)=
sort[b|b←x;b<=a]++
[a]++
sort [b|b←x;b>a]
LazyEvaluation
 Alanguageisstrictifitrequiresallactualparameterstobefullyevaluated
 Alanguageisnonstrictifitdoesnothavethestrictrequirement
 Nonstrictlanguagesaremoreefficientandallowsomeinterestingcapabilities
– infinitelists
 Lazyevaluation-Onlycomputethosevaluesthatarenecessary
 Positivenumbers
positives=[0..]
 Determiningif16isasquarenumber
member[]b=False
member(a:x)b=(a==b)||memberxb
squares=[n * n|n← [0..]]
membersquares16
MemberRevisited
 Thememberfunctioncouldbewrittenas:me
mber[]b=False
member(a:x)b=(a==b)||memberxb
 However,thiswouldonlyworkiftheparametertosquareswasaperfectsquare;ifnot,itwil
lkeepgeneratingthemforever.Thefollowingversionwillalwayswork:
member2(m:x)n
|m<n=member2xn
|m==n=True
|otherwise=False

ApplicationsofFunctionalLanguages–CO5
 APLisusedforthrow-awayprograms
 LISPisusedforartificialintelligence
– Knowledgerepresentation
– Machinelearning
– Naturallanguageprocessing
– Modelingofspeechandvision
 Schemeisusedtoteachintroductoryprogrammingatsomeuniversities

90
ComparingFunctionalandImperativeLanguages
 ImperativeLanguages:
– Efficientexecution
– Complexsemantics
– Complexsyntax
– Concurrencyisprogrammerdesigned
 FunctionalLanguages:
– Simplesemantics
– Simplesyntax
– Inefficientexecution
– Programscanautomaticallybemadeconcurrent

SummaryofFunctionalProgrammingLanguages
 Functionalprogramminglanguagesusefunctionapplication,conditionalexpression
s,recursion,andfunctionalformstocontrolprogramexecutioninsteadofimperativef
eaturessuchasvariablesandassignments
 LISPbeganasapurelyfunctionallanguageandlaterincludedimperativefeatures
 SchemeisarelativelysimpledialectofLISPthatusesstaticscopingexclusively
 COMMONLISPisalargeLISP-basedlanguage
 MLisastatic-
scopedandstronglytypedfunctionallanguagewhichincludestypeinference,excepti
onhandling,andavarietyofdatastructuresandabstractdatatypes
 Haskellisalazyfunctionallanguagesupportinginfinitelistsandsetcomprehension.
 Purelyfunctionallanguageshaveadvantagesoverimperativealternatives,buttheirl
owerefficiencyonexistingmachinearchitectureshaspreventedthemfromenjoying
widespreaduse

Pragmatics
Asoftwaresystemoftenconsistsofanumberofsubsystemscontrolledorconnectedbyascript.
Scriptingisaparadigmcharacterizedby:
 Useofscriptstogluesubsystemstogether.
 Rapiddevelopmentandevolutionofscripts.
 Modestefficiencyrequirements.
 Veryhigh-levelfunctionalityinapplication-specificareas.

KeyConcepts
Thefollowingconceptsarecharacteristicofscriptinglanguages:
 Veryhigh-levelstringprocessing.
 Veryhigh-levelgraphicaluserinterfacesupport.
 Dynamictyping.

CaseStudy:PYTHON
 PYTHONwasdesignedintheearly1990sbyGuidovanRossum.
 IthasbeenusedtohelpimplementthesuccessfulWebsearchengineGOOGLE,andinav
arietyofotherapplicationareasrangingfromsciencefiction(visualeffectsfortheStar
Warsseries)torealscience(computer-aideddesigninNASA).

91
ValuesandTypes
 PYTHONhasalimitedrepertoireofprimitivetypes:integer,real,andcomplexnumbers.
 Ithasnospecificcharactertype;single-
characterstringsareusedinstead.Itsbooleanvalues(namedFalseandTrue)arejusts
mallintegers.
 PYTHONhasarichrepertoireofcompositetypes:tuples,strings,lists,dictionariesandobj
ects.APYTHONlistisaheterogeneoussequenceofvalues.
 Adictionary(sometimescalledanassociativearray)isaheterogeneousmappingfromkey
stovalues,wherethekeysaredistinctimmutablevalues.
 Thefollowingcodeillustratestupleconstruction:
date=1998,"Nov",19
Nowdate[0]yields1998,date[1]yields‘‘Nov’’,anddate[2]yields19.

 The following code illustrates two list constructions, which construct


ahomogeneouslistandaheterogeneouslist,respectively:
primes=[2,3,5,7,11]
years=["unknown",1314,1707,date[0]]
Nowprimes[0]yields2,years[1]yields1314,years[3]yields1998,‘‘years[0]=843’’up
datesthefirstcomponentofyears,andsoon.Also,‘‘years.append(1999)’’
adds1999attheendofyears.

 Thefollowingcodeillustratesdictionaryconstruction:
phones={"David":6742,"Carol":6742,"Ali":6046}
Nowphones["Carol"]yields6742,phones["Ali"]yields6046,‘‘phones["Ali"]=1234’’
updatesthecomponentofphoneswhosekeyis‘‘Ali’’,andsoon.Also,‘‘David”inphonesret
urnsTrue,and‘‘phones.keys()’’returnsalistcontaining‘‘Ali’’,‘‘Carol’’,and‘‘David’’
(innoparticularorder).

Variables,StorageandControl
 PYTHONsupportsglobalandlocalvariables.
 Variablesarenotexplicitlydeclared,simplyinitializedbyassignment.Afterinitializat
ion,avariablemaylaterbeassignedanyvalueofanytype.
 PYTHON’srepertoireofcommandsincludeassignments,procedurecalls,conditional(if-
butnotcase-)commands,iterative(while-andfor-)commandsandexception-
handlingcommands.
 However,PYTHONdiffersfromCinnotallowinganassignmenttobeusedasanexpress
ion.
 PYTHONadditionallysupportssimultaneousassignment.
 Forexample:
y,m,d=date
assignsthethreecomponentsofthetupledatetothreeseparatevariables.Also:
m,n=n,m
conciselyswapsthevaluesoftwovariablesmandn.(Actually,itfirstconstructsapair,the
nassignsthetwocomponentsofthepairtothetwoleft-sidevariables)
 PYTHONif-andwhile-commandsareconventional.
 PYTHONfor-commandssupportdefiniteiteration.
 Wecaneasilyachievetheconventionaliterationoverasequenceofnumbersbyusingtheli
braryprocedurerange(m,n),whichreturnsalistofintegersfrommthroughn−1.

92
 PYTHONsupportsbreak,continue,andreturnsequencers.Italsosupportsexception
s,whichareobjectsofasubclassofException,andwhichcancarryvalues.

 ThefollowingcodecomputestheGreatestCommonDivisoroftwointegers,mandn:
p,q=m,n
whilep%q!=0:
p,q=q,p%qgcd=q
 Notetheeleganceofsimultaneousassignment.
 Notealsothatindentationisrequiredtoindicatetheextentoftheloopbody.
 Thefollowingcodesumsthenumericcomponentsofalistrow,ignoringanynonnumericc
omponents:
sum=0.0
forxinrow:
ifisinstance(x,(int,float)):su
m+=x

PYTHONExceptions
 Thefollowingcodepromptstheusertoenteranumericliteral,andstoresthecorrespondi
ngrealnumberinnum:
whileTrue:
try:
response=raw_input("Enteranumericliteral:")nu
m=float(response)
break
exceptValueError:
print"Yourresponsewasill-formed."
Thiswhile-commandkeepspromptinguntiltheuserentersawell-
formednumericliteral.Thelibraryprocedureraw_input(...)displaysthegivenpromp
tandreturnstheuser’sresponseasastring.Thetypeconversion‘‘float(response)’’
attemptstoconverttheresponsetoarealnumber.Ifthistypeconversionispossible,th
efollowingbreaksequencerterminatestheloop.Ifnot,thetypeconversionthrowsaV
alueErrorexception,controlistransferredtotheValueErrorexceptionhandler,whic
hdisplaysawarningmessage,andfinallytheloopisiteratedagain.

BindingsandScope
 APYTHONprogramconsistsofanumberofmodules,whichmaybegroupedintopackages.
 Withinamodulewemayinitializevariables,defineprocedures,anddeclareclasses.Withi
naprocedurewemayinitializelocalvariablesanddefinelocalprocedures.Withinaclassw
emayinitializevariablecomponentsanddefineprocedures(methods).
 DuringaPYTHONsession,wemayinteractivelyissuedeclarations,commands,andex
pressionsfromthekeyboard.
 Theseareallacteduponimmediately.Wheneverweissueanexpression,itsvalueisdispla
yedonthescreen.Wemayalsoimportanamedmodule(orselectedcomponentsofit)atan
ytime.
 PYTHONwasoriginallyadynamically-scopedlanguage,butitisnowstaticallyscoped.

93
ProceduralAbstraction
 PYTHONsupportsfunctionproceduresandproperprocedures.
 Theonlydifferenceisthatafunctionprocedurereturnsavalue,whileaproperprocedurer
eturnsnothing.
 SincePYTHONisdynamicallytyped,aproceduredefinitionstatesthenamebutnotthetyp
eofeachformalparameter.Thecorrespondingargumentmaybeofdifferenttypesondiffe
rentcallstotheprocedure.

PYTHONProcedures
 Thefollowingfunctionprocedurereturnsthegreatestcommondivisorofitstwoargumen
ts:
defgcd(m,n):
p,q=m,n
whilep%q!=0:p,q=
q,p%q
returnq
Herepandqarelocalvariables.
 ThefollowingproperproceduretakesadaterepresentedbyatripleandprintsthatdateinI
SOformat(e.g.,‘‘2000-01-01’’):
defprint_date(date):y
,m,d=date
ifm="Jan":m=
1
elifm="Feb":m=
2
...
elifm="Dec":m=
12
print"%04d-%02d-%02d"%(y,m,d)
Herey,m,anddarelocalvariables.

PYTHONprocedurewithdynamictyping
 Thefollowingfunctionprocedureillustratestheflexibilityofdynamictyping.Itreturnsth
eminimumandmaximumcomponentofagivensequence:
defminimax(vals):
min=max=vals[0]
forvalinvals:
ifval<min:
min=val
elifval>max:max=
val
returnmin,max
 Inacalltothisprocedure,theargumentmaybeeitheratupleoralist.
 Ineffectithastworesults,whichwecaneasilyseparateusingsimultaneousassignmen
t:
readings=[...]
low,high=minimax(readings)
 SomeolderlanguagessuchasChavelibraryprocedureswithvariablenumbersofargu
ments.
 PYTHONisalmostuniqueinallowingsuchprocedurestobedefinedbyprogrammers.
 Thisisachievedbythesimpleexpedientofallowingasingleformalparametertorefertoaw
holetuple(ordictionary)ofarguments.

94
PYTHONprocedurewithavariablenumberofarguments
 Thefollowingproperprocedureacceptsanynumberofarguments,andprintsthemonepe
rline:
defprintall(*args):
forarginargs:
printarg
 Thenotation‘‘*args’’declaresthatargswillrefertoatupleofarguments.
 Allofthefollowingprocedurecallsworksuccessfully:
printall(name)printall(na
me,address)
printall(name,address,zipcode)

DataAbstraction
 PYTHONhasthreedifferentconstructsrelevanttodataabstraction:packages,modul
es,andclasses.
 Modulesandclassessupportencapsulation,usinganamingconventiontodistinguish
betweenpublicandprivatecomponents.
 Apackageissimplyagroupofmodules.Amoduleisagroupofcomponentsthatmaybev
ariables,procedures,andclasses.
 Thesecomponentsmaybeimportedforusebyanyothermodule.Allcomponentsofamod
ulearepublic,exceptthosewhoseidentifiersstartwith‘‘_’’ whichareprivate.
 Aclassisagroupofcomponentsthatmaybeclassvariables,classmethods,andinstanc
emethods.Aproceduredefinedinaclassdeclarationactsasaninstancemethodifitsfir
stformalparameterisnamedselfandreferstoanobjectoftheclassbeingdeclared.Oth
erwisetheprocedureactsasaclassmethod.
 Toachievetheeffectofaconstructor,weusuallyequipeachclasswithaninitializationmet
hodnamed‘‘init’’;thismethodisautomaticallycalledwhenanobjectoftheclassisconstruc
ted.Instancevariablesarenamedusingtheusual‘‘.’’Notation(asinself.attr),andtheymay
beinitializedbytheinitializationmethodorbyanyothermethod.Allcomponentsofaclass
arepublic,exceptthosewhoseidentifiersstartwith‘‘’’,whichareprivate.

PYTHONClass
 Considerthefollowingclass:
classPerson:
definit(self,sname,fname,gender,birth):self.sur
name=sname
self.forename=fname
self.female=(gender=="F"orgender=="f")self.birt
h=birth
defget_surname(self):
returnself.surname
defchange_surname(self,sname):sel
f.surname=sname
defprint_details(self):
printself.forename+""+self.surname
 Thisclassisequippedwithaninitializationmethodandthreeotherinstancemethods,eac
hofwhichhasaselfparameterandperhapssomeotherparameters.Inthefollowingcode:
dw=Person("Watt","David","M",1946)

95
theobjectconstructionontherightfirstcreatesanobjectofclassPerson;itthenpassesthea
bovearguments,togetherwithareferencetothenewlycreatedobject,totheinitialization
method.Thelatterinitializestheobject’sinstancevariables,whicharenamedsurname,fo
rename,female,andbirth(andthusareallprivate).
 PYTHONsupportsmultipleinheritance:aclassmaydesignateanynumberofsupercla
sses.Ambiguousreferencestoclasscomponentsareresolvedbysearchingthesuperc
lassesintheorderinwhichtheyarenamedintheclassdeclaration.
 PYTHON’ssupportforobject-
orientedprogrammingisdevelopingbutisnotyetmature.Theuseofthe‘‘’’
namingconventiontoindicateprivacyisclumsyanderror-
prone;classcomponentsarepublicbydefault.Stillmoreseriously,variablecomponentsc
anbecreated(anddeleted)atanytime,byanymethodandevenbyapplicationcode.

SeparateCompilation
 PYTHONmodulesarecompiledseparately.Eachmodulemustexplicitlyimportevery
othermoduleonwhichitdepends.Eachmodule’ssourcecodeisstoredinatextfile.
 Forexample,amodulenamedwidgetisstoredinafilenamedwidget.py.Whenthatmo
duleisfirstimported,itiscompiledanditsobjectcodeisstoredinafilenamedwidget.p
yc.
 Wheneverthemoduleissubsequentlyimported,itisrecompiledonlyifthesourcecod
ehasbeeneditedinthemeantime.Compilationiscompletelyautomatic.
 ThePYTHONcompilerdoesnotrejectcodethatreferstoundeclaredidentifiers.Suchcode
simplyfailsifandwhenitisexecuted.
ModuleLibrary
 PYTHONisequippedwithaveryrichmodulelibrary,whichsupportsstringhandling,mar
kup,mathematicsandcryptography,multimedia,GUIs,operatingsystemservices,Intern
etservices,compilation,andsoon.
 Unlikeolderscriptinglanguages,PYTHONdoesnothavebuilt-inhigh-
levelstringprocessingorGUIsupport.Instead,thePYTHONmodulelibraryprovidess
uchfunctionality.Forexample,therelibrarymoduleprovidespowerfulstringmatchi
ngfacilitiesusingregularexpressions.

SummaryofScriptingLanguages
 Thepragmaticissuesthatinfluencethedesignofscriptinglanguages:gluing,rapiddev
elopmentandevolution,modestefficiencyrequirements,andveryhigh-
levelfunctionalityinrelevantareas.
 Theconceptscommontomostscriptinglanguages:veryhigh-
levelsupportforstringprocessing,veryhigh-
levelsupportforGUIs,anddynamictyping.
 ThedesignofamajorscriptinglanguagePYTHON,resemblesaconventionalprogrammin
glanguage,exceptthatitisdynamicallytyped,andthatitderivesmuchofitsexpressivenes
sfromarichmodulelibrary.

96

You might also like