0% found this document useful (0 votes)
10 views161 pages

PPL Notes Pet

The document discusses principles of programming languages over multiple units. It covers preliminary concepts like reasons for studying programming languages, influences on language design, and categories of languages. It also discusses data types, expressions, statements, control structures, subprograms, abstract data types, functional programming languages and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views161 pages

PPL Notes Pet

The document discusses principles of programming languages over multiple units. It covers preliminary concepts like reasons for studying programming languages, influences on language design, and categories of languages. It also discusses data types, expressions, statements, control structures, subprograms, abstract data types, functional programming languages and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 161

PrinciplesofProgrammingLanguages

PE
SUBJECT CODE : CCS358

SUBJECT NAME :PRINCIPLES OF PROGRAMMING LANGUAGES

REGULATION :2021

ACADEMIC YEAR :2023-2024(EVEN)

YEAR/SEM :III/VI

[Ms.P.JENIFER,AP/CSE] [Dr.BABU RENGA RAJAN,HOD/CSE]

PREPARED BY HEAD OF THE DEPARTMENT

PET ENGINEERING COLLEGE


CONTENTS

UNIT1.PRELIMINARYCONCEPTS
1.1 ReasonsforStudyingConceptsofProgrammingLanguages
1.2 ProgrammingDomains,LanguageEvaluationCriteria
1.3 InfluencesonLanguageDesign,LanguageCategories
1.4 ProgrammingParadigms-Imperative,FunctionalProgramminglanguage
1.5 LanguageImplementation-compilationandinterpretation
1.6 Programmingenvironments

SYNTAXANDSEMANTICS

1.7 TheGeneralProblemsofDescribingSyntaxandsemantics
1.8 BNF
1.9 EBNFforcommonprogramminglanguagefeatures
1.10 AmbiguousGrammar

UNIT2.DATATYPESANDVARIABLES
2.1 IntroductiontoPrimitiveDataTypes
2.2 User-DefinedDataTypesandArrayTypes
2.3 Record,UnionandPointerandReferencetypes
2.4 Names,Variables,TheConceptofBinding
2.5 TypeChecking,TypeCompatibility
2.6 StrongTypes,NamedConstants,variableinitialization

EXPRESSIONSANDSTATEMENTS&CONTROLSTRUCTURES

2.7 Expression:[Arithmetic,RelationalandBooleanExpressions]
2.8 Short-CircuitEvaluation
2.9 AssignmentStatements,Mixed-
ModeAssignment[ReferentialTransparency&FunctionalProgramming]
2.10 ControlStructures[statementLevelControlStructures,Compoundstatements]
2.11 SelectionStatements,IterativeStatements,UnconditionalBranching,GuardedCom
mands

UNIT3.SUBPROGRAMSANDBLOCKS
3.1 FundamentalsofSubprograms
3.2 DesignIssuesforSubprograms

PET ENGINEERING COLLEGE


3.3 ParameterPassingMethods
3.4 ParametersSubprogramsasparameters
3.5 OverloadedSubprograms&Operations
3.6 GenericSubprograms,separatelycompiledmodules
3.7 Co-Routines

PET ENGINEERING COLLEGE


UNITIV.ABSTRACTDATATYPES

4.1 Abstract-datatypes[Abstraction&Encapsulation]
4.2 IntroductiontoDataAbstraction,DesignIssues
4.3 LanguageExamples
4.4 C++ParameterizedAbstractDataTypes
4.5 DataTypes
4.6 Object-OrientedProgramminginSmalltalk
4.7 Object-OrientedProgramminginC++
4.8 Object-OrientedProgramminginJava
4.9 Object-OrientedProgramminginC#
4.10 Object-OrientedProgramminginAda95

EXCEPTIONHANDLING&LOGICPROGRAMMING

4.11 ExceptionHandling:Exceptions,ExceptionPropagation
4.12 ExceptionHandlerinAda
4.13 C++andJava
4.14 Logic Programming Language : Introduction An Overview of Logic
Programming
4.15 TheBasicElementsofPROLOG
4.16 ApplicationsofLogicProgramming

UNIT-V.FUNCTIONALPROGRAMMINGLANGUAGES&SCRIPTINGLANGUAGE

5.1 FunctionalProgrammingLanguageIntroduction
5.2 FundamentalsofFunctionalProgrammingLanguages,LISPProgramming
5.3 FundamentalsofML,examples
5.4 FundamentalsofHaskell,functionsyntaxandexamples
5.5 Applications of Functional Programing language and Comparison
ofFunctionalandImperativeLanguages

PET ENGINEERING COLLEGE


UNIT-1
PreliminaryConcepts

Background
 Frankly,wedidn‘thavethevaguestideahowthething[FORTRANlanguageandcompiler] would
work out in detail. …We struck out simply to optimize the
objectprogram,therunningtime,becausemostpeopleatthattimebelievedyoucouldn‘tdothatkindo
fthing.Theybelievedthatmachined-
codedprogramswouldbesoinefficientthatitwouldbeimpracticalformanyapplications.
 JohnBackus,unexpectedsuccessesarecommon–
thebrowserisanotherexampleofanunexpectedsuccess

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

1.2 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),general-
purpose(e.g.,Java)

PET ENGINEERING COLLEGE


1.2 LanguageEvaluationCriteria–CO1,CO2

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

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

PET ENGINEERING COLLEGE


 Compilingprograms
 Executingprograms

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


1.3 InfluencesonLanguageDesign-CO3
 ComputerArchitecture
– Languagesaredevelopedaroundtheprevalentcomputerarchitecture,knownasthevonNeuman
narchitecture
 ProgrammingMethodologies
– Newsoftwaredevelopmentmethodologies(e.g.,object-
orientedsoftwaredevelopment)ledtonewprogrammingparadigmsandbyextension,newprogram
minglanguages

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

Figure1.1ThevonNeumannComputerArchitecture

ProgrammingMethodologies
 1950sandearly1960s:Simpleapplications;worryaboutmachineefficiency
 Late1960s:Peopleefficiencybecameimportant;readability,bettercontrolstructures

PET ENGINEERING COLLEGE


– structuredprogramming
– top-downdesignandstep-wiserefinement
 Late1970s:Process-orientedtodata-oriented
– dataabstraction
 Middle1980s:Object-orientedprogramming
– Dataabstraction+inheritance+polymorphism

PET ENGINEERING COLLEGE


1.4 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,butusedtospecifythelayoutofinformationinWebdocuments
– Examples:XHTML,XML

LanguageDesignTrade-Offs
 Reliabilityvs.costofexecution
– Conflictingcriteria
– Example:Javademandsallreferencestoarrayelementsbecheckedforproperindexingbutthatleadst
oincreasedexecutioncosts
 Readabilityvs.writability
– Anotherconflictingcriteria
– Example:APLprovidesmanypowerfuloperators(andalargenumberofnewsymbols),allowingco
mplexcomputationstobewritteninacompactprogrambutatthecostofpoorreadability
 Writability(flexibility)vs.reliability
– Anotherconflictingcriteria
– Example:C++pointersarepowerfulandveryflexiblebutnotreliablyused

1.5ImplementationMethods-CO2
 Compilation
– Programsaretranslatedintomachinelanguage
 PureInterpretation
– Programsareinterpretedbyanotherprogramknownasaninterpreter
 HybridImplementationSystems
– Acompromisebetweencompilersandpureinterpreters
Compilation
 Translatehigh-levelprogram(sourcelanguage)intomachinecode(machinelanguage)
 Slowtranslation,fastexecution

PET ENGINEERING COLLEGE


 Compilationprocesshasseveralphases:
– lexicalanalysis:convertscharactersinthesourceprogramintolexicalunits
– syntaxanalysis:transformslexicalunitsintoparsetreeswhichrepresentthesyntacticstructureof
program
– Semanticsanalysis:generateintermediatecode
– codegeneration:machinecodeisgenerated

PET ENGINEERING COLLEGE


Figure1.2LayeredViewofComputer:Theoperatings
ystemandlanguageimplementationarelayeredover
Machineinterfaceofacomputer Figure1.3TheCompilationProcess

AdditionalCompilationTerminologies
 Loadmodule(executableimage):theuserandsystemcodetogether
 Linkingandloading:theprocessofcollectingsystemprogramandlinkingthemtouserprogram
ExecutionofMachineCode
 Fetch-execute-cycle(onavonNeumannarchitecture)
initializetheprogramcounterre
peatforever
fetchtheinstructionpointedbythecounterincreme
ntthecounter
decodetheinstructionexecut
etheinstruction
endrepeat
VonNeumannBottleneck
 Connectionspeedbetweenacomputer‘smemoryanditsprocessordeterminesthespeedofacomputer
 Programinstructionsoftencanbeexecutedalotfasterthantheaboveconnectionspeed;theconnectio
nspeedthusresultsinabottleneck
 KnownasvonNeumannbottleneck;itistheprimarylimitingfactorinthespeedofcomputers

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

PET ENGINEERING COLLEGE


 Oftenrequiresmorespace
 Becomingrareonhigh-levellanguages

PET ENGINEERING COLLEGE


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

HybridImplementationSystems
 Acompromisebetweencompilersandpureinterpreters
 Ahigh-levellanguageprogramistranslatedtoanintermediatelanguagethatallowseasyinterpretation
 Fasterthanpureinterpretation
 Examples
– Perlprogramsarepartiallycompiledtodetecterrorsbeforeinterpretation
– InitialimplementationsofJavawerehybrid;theintermediateform,bytecode,providesportabilitytoa
nymachinethathasabytecodeinterpreterandaruntimesystem(together,thesearecalledJavaVirtual
Machine)

Figure1.4PureInterpreataion Figure1.5HybridImplementation

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

1.6 Preprocessors-CO2
 Preprocessormacros(instructions)arecommonlyusedtospecifythatcodefromanotherfileistobeinclud
ed

PET ENGINEERING COLLEGE


 Apreprocessorprocessesaprogramimmediatelybeforetheprogramiscompiledtoexpandembeddedpre
processormacros
 Awell-knownexample:Cpreprocessor
– expands#include,#define,andsimilarmacros

PET ENGINEERING COLLEGE


SyntaxandSemantics

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

1.7 TheGeneralProblemofDescribingSyntax–CO1
 Asentenceisastringofcharactersoversomealphabet
 Alanguageisasetofsentences
 Alexemeisthelowestlevelsyntacticunitofalanguage(e.g.,*,sum,begin)
 Atokenisacategoryoflexemes(e.g.,identifier)
 LanguagesRecognizers
– Arecognitiondevicereadsinputstringsofthelanguageanddecideswhethertheinputstringsbelongto
thelanguage
– Example:syntaxanalysispartofacompiler
 LanguagesGenerators
– Adevicethatgeneratessentencesofalanguage
– Onecandetermineifthesyntaxofaparticularsentenceiscorrectbycomparingittothestructureoftheg
enerator

1.8 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
PET ENGINEERING COLLEGE
 Non-terminals:BNFabstractions
 Terminals:lexemesandtokens
 Grammar:acollectionofrules
– ExamplesofBNFrules:

PET ENGINEERING COLLEGE


<ident_list>→identifier|identifer,<ident_list>
BNFRules <if_stmt>→if<logic_expr>then<stmt>
 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,startingwiththestartsymbolandendingwithasentence
(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
<program><stmts> Figure2.1ParseTree
 <stmt>
 <var>=<expr>
 a=<expr>
 a=<term>+<term>
 a=<var>+<term>
 a=b+<term>
 a=b+const

Derivation
 Everystringofsymbolsinthederivationisasententialform
 Asentenceisasententialformthathasonlyterminalsymbols
 Aleftmostderivationisoneinwhichtheleftmostnonterminalineachsententialformistheonethatisexpan
ded
 Aderivationmaybeneitherleftmostnorrightmost

AmbiguityinGrammars
 Agrammarisambiguousiffitgeneratesasententialformthathastwoormoredistinctparsetrees
AnUnambiguousExpressionGrammar

PET ENGINEERING COLLEGE


Ifweusetheparsetreetoindicateprecedencelevelsoftheoperators,wecannothaveambiguity
<expr>→<expr>-<term>|<term>
<term>→<term>/const|const

PET ENGINEERING COLLEGE


Figure2.2AnAmbiguousExpressionGrammar Figure2.3AnUnambiguousExpression
Grammar

AssociativityofOperators Figure2.4ParseTreeforA
Operatorassociativitycanalsobeindicatedbyagrammar ssociativityoperator
<expr>→<expr>+<expr>|
const(ambiguous)
<expr>→<expr>+const|
const(unambiguous)

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

<expr>→<term>{(+|-)<term>}
<term>→<factor>{(*|/)<factor>}

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

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


– Eachrulehasasetoffunctionsthatdefinecertainattributesofthenonterminalsintherule
– 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,eithersimulatedorac
tual.Thechangeinthestateofthemachine(memory,registers,etc.)definesthemeaningofthestat
ement
 Touseoperationalsemanticsforahigh-levellanguage,avirtualmachineisneeded
 Ahardwarepureinterpreterwouldbetooexpensive
 Asoftwarepureinterpreteralsohasproblems:
– Thedetailedcharacteristicsoftheparticularcomputerwouldmakeactionsdifficulttounderstan
d
– Suchasemanticdefinitionwouldbemachine-dependent

PET ENGINEERING COLLEGE


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

AxiomaticSemantics
 Anassertionbeforeastatement(aprecondition)statestherelationshipsandconstraintsamongvariab
lesthataretrueatthatpointinexecution
 Anassertionfollowingastatementisapostcondition
 Aweakestpreconditionistheleastrestrictivepreconditionthatwillguaranteethepostcondition
 Pre-postform:{P}statement{Q}
 Anexample:a=b+1{a>1}
 Onepossibleprecondition:{b>10}
 Weakestprecondition:{b>0}
 Programproofprocess:Thepostconditionforthewholeprogramisthedesiredresult.Workbackthrought
heprogramtothefirststatement.Ifthepreconditiononthefirststatementisthesameastheprogramspec,th
eprogramiscorrect.
 Anaxiomforassignmentstatements(x=E):
{Qx->E}x=E{Q}
 Aninferenceruleforsequences
– ForasequenceS1;S2:
– {P1}S1{P2}
– {P2}S2{P3}
 AninferenceruleforlogicalpretestloopsFortheloop
construct:
{P}whileBdoSend{Q}Characteristicsoft
heloopinvariantImustmeetthefollowingcond
itions:
– P=>I(theloopinvariantmustbetrueinitially)
– {I}B{I}(evaluationoftheBooleanmustnotchangethevalidityofI)
– {IandB}S{I}(Iisnotchangedbyexecutingthebodyoftheloop)
– (Iand(notB))=>Q(ifIistrueandBisfalse,Qisimplied)
– Theloopterminates(thiscanbedifficulttoprove)
 TheloopinvariantIisaweakenedversionofthelooppostcondition,anditisalsoaprecondition.

PET ENGINEERING COLLEGE


 Imustbeweakenoughtobesatisfiedpriortothebeginningoftheloop,butwhencombinedwiththeloo
pexitcondition,itmustbestrongenoughtoforcethetruthofthepostcondition.

EvaluationofAxiomaticSemantics:
– Developingaxiomsorinferencerulesforallofthestatementsinalanguageisdifficult
– Itisagoodtoolforcorrectnessproofs,andanexcellentframeworkforreasoningaboutprograms,butiti
snotasusefulforlanguageusersandcompilerwriters
– Itsusefulnessindescribingthemeaningofaprogramminglanguageislimitedforlanguageusersorco
mpilerwriters

DenotationalSemantics
– Basedonrecursivefunctiontheory
– Themostabstractsemanticsdescriptionmethod
– OriginallydevelopedbyScottandStrachey(1970)
– Theprocessofbuildingadenotationalspecforalanguage(notnecessarilyeasy):
– Defineamathematicalobjectforeachlanguageentity
– Defineafunctionthatmapsinstancesofthelanguageentitiesontoinstancesofthecorrespondingmath
ematicalobjects
– Themeaningoflanguageconstructsaredefinedbyonlythevaluesoftheprogram'svariables
– Thedifferencebetweendenotationalandoperationalsemantics:Inoperationalsemantics,thestatech
angesaredefinedbycodedalgorithms;indenotationalsemantics,theyaredefinedbyrigorousmathe
maticalfunctions
– Thestateofaprogramisthevaluesofallitscurrentvariables
s={<i1,v1>,<i2,v2>,…,<in,vn>}
– LetVARMAPbeafunctionthat,whengivenavariablenameandastate,returnsthecurrentvalueo
fthevariable
VARMAP(ij,s)=vj
 DecimalNumbers
– Thefollowingdenotationalsemanticsdescriptionmapsdecimalnumbersasstringsofsymbolsinton
umericvalues
<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
(<dec_num>'1’)=10*Mdec(<dec_num>)+1

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

Expressions
 MapexpressionsontoZ{error}
 Weassumeexpressionsaredecimalnumbers,variables,orbinaryexpressionshavingonearithmeticoper
atorandtwooperands,eachofwhichcanbeanexpression
 AssignmentStatements
– Mapsstatesetstostatesets
 LogicalPretestLoops
– Mapsstatesetstostatesets

PET ENGINEERING COLLEGE


 Themeaningoftheloopisthevalueoftheprogramvariablesafterthestatementsintheloophavebeenexecu
tedtheprescribednumberoftimes,assumingtherehavebeennoerrors
 Inessence,theloophasbeenconvertedfromiterationtorecursion,wheretherecursivecontrolismathemat
icallydefinedbyotherrecursivestatemappingfunctions
 Recursion,whencomparedtoiteration,iseasiertodescribewithmathematicalrigor
 Evaluationofdenotationalsemantics
– Canbeusedtoprovethecorrectnessofprograms
– Providesarigorouswaytothinkaboutprograms
– Canbeanaidtolanguagedesign
– Hasbeenusedincompilergenerationsystems
– Becauseofitscomplexity,theyareoflittleusetolanguageusers

Summary
 BNFandcontext-freegrammarsareequivalentmeta-languages
– Well-suitedfordescribingthesyntaxofprogramminglanguages
 Anattributegrammarisadescriptiveformalismthatcandescribeboththesyntaxandtheseman
ticsofalanguage
 Threeprimarymethodsofsemanticsdescription
– Operation,axiomatic,denotational

PET ENGINEERING COLLEGE


UNIT-2
DataTypesandVariables

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

2.1 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-
PointStandard754
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

PET ENGINEERING COLLEGE


Character
 Storedasnumericcoding
 Mostcommonlyusedcoding:ASCII
 Analternative,16-bitcoding:Unicode

PET ENGINEERING COLLEGE


– 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‘scharacters,ratherthan
maintainingthelength
 Dynamic(nomaximum):SNOBOL4,Perl,JavaScript
 Adasupportsallthreestringlengthoptions
Evaluation
 Aidtowritability
 Asaprimitivetypewithstaticlength,theyareinexpensivetoprovide—whynothavethem?
 Dynamiclengthisnice,butisitworththeexpense?
Implementation
 Staticlength:compile-timedescriptor
 Limiteddynamiclength:mayneedarun-timedescriptorforlength(butnotinCandC++)

PET ENGINEERING COLLEGE


 Dynamiclength:needrun-timedescriptor;allocation/de-
allocationisthebiggestimplementationproblem

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

PET ENGINEERING COLLEGE


2.2 User-DefinedOrdinalTypes-CO2
 Anordinaltypeisoneinwhichtherangeofpossiblevaluescanbeeasilyassociatedwiththesetofpositi
veintegers
 ExamplesofprimitiveordinaltypesinJava
– integer
– char
– boolean

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

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

SubrangeTypes
 Anorderedcontiguoussubsequenceofanordinaltype
– Example:12..18isasubrangeofintegertype
 Ada‘sdesign
typeDaysis(mon,tue,wed,thu,fri,sat,sun);su
btypeWeekdaysisDaysrangemon..fri;subtyp
eIndexisIntegerrange1..100;

Day1:Days;D
ay2:Weekday;
Day2:=Day1;

SubrangeEvaluation
 Aidtoreadability
– Makeitcleartothereadersthatvariablesofsubrangecanstoreonlycertainrangeofvalues
 Reliability
– Assigningavaluetoasubrangevariablethatisoutsidethespecifiedrangeisdetectedasanerror

Implementation

PET ENGINEERING COLLEGE


 Enumerationtypesareimplementedasintegers
 Subrangetypesareimplementedliketheparenttypeswithcodeinserted(bythecompiler)torestrictassign
mentstosubrangevariables

PET ENGINEERING COLLEGE


ArrayTypes
 Anarrayisanaggregateofhomogeneousdataelementsinwhichanindividualelementisidentifiedbyitsp
ositionintheaggregate,relativetothefirstelement.
ArrayDesignIssues
 Whattypesarelegalforsubscripts?
 Aresubscriptingexpressionsinelementreferencesrangechecked?
 Whenaresubscriptrangesbound?
 Whendoesallocationtakeplace?
 Whatisthemaximumnumberofsubscripts?
 Canarrayobjectsbeinitialized?
 Areanykindofslicessupported?
ArrayIndexing
 Indexing(orsubscripting)isamappingfromindicestoelements
array_name(index_value_list)anelement
 IndexSyntax
– FORTRAN,PL/I,Adauseparentheses
 Adaexplicitlyusesparenthesestoshowuniformitybetweenarrayreferencesandfunctioncallsbecauseb
otharemappings
– 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,buttheallocationisdoneatdeclarationtime
– Advantage:spaceefficiency
 Stack-dynamic:subscriptrangesare

dynamicallyboundandthestorageallocationisdynamic(doneatrun-time)
– Advantage:flexibility(thesizeofanarrayneednotbeknownuntilthearrayistobeused)
 Fixedheap-dynamic:similartofixedstack-
dynamic:storagebindingisdynamicbutfixedafterallocation(i.e.,bindingisdonewhenrequestedandsto
rageisallocatedfromheap,notstack)
 Heap-
dynamic:bindingofsubscriptrangesandstorageallocationisdynamicandcanchangeanynumberof
times
– Advantage:flexibility(arrayscangroworshrinkduringprogramexecution)

PET ENGINEERING COLLEGE


 CandC++arraysthatincludestaticmodifierarestatic
 CandC++arrayswithoutstaticmodifierarefixedstack-dynamic
 CandC++providefixedheap-dynamicarrays
 C#includesasecondarrayclassArrayListthatprovidesfixedheap-dynamic
 Perl,JavaScript,Python,andRubysupportheap-dynamicarrays

PET ENGINEERING COLLEGE


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
 APLprovidesthemostpowerfularrayprocessingoperationsforvectorsandmatrixesaswellasunaryoper
ators(forexample,toreversecolumnelements)
 Adaallowsarrayassignmentbutalsocatenation
 Python‘sarrayassignments,buttheyareonlyreferencechanges.Pythonalsosupportsarraycatenati
onandelementmembershipoperations
 Rubyalsoprovidesarraycatenation
 Fortranprovideselementaloperationsbecausetheyarebetweenpairsofarrayelements
– Forexample,
+operatorbetweentwoarraysresultsinanarrayofthesumsoftheelementpairsofthetwoarrays
RectangularandJaggedArrays
 Arectangulararrayisamulti-
dimensionedarrayinwhichalloftherowshavethesamenumberofelementsandallcolumnshavethesame
numberofelements
 Ajaggedmatrixhasrowswithvaryingnumberofelements
– Possiblewhenmulti-dimensionedarraysactuallyappearasarraysofarrays
 C,C++,andJavasupportjaggedarrays
 Fortran,Ada,andC#supportrectangulararrays(C#alsosupportsjaggedarrays)
Slices
 Asliceissomesubstructureofanarray;nothingmorethanareferencingmechanism
 Slicesareonlyusefulinlanguagesthathavearrayoperations

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

Vector(3:6)isafourelementarray

ImplementationofArrays

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


AccessingMulti-dimensionedArrays Figure3.4LocatinganElementin
aMulti-dimensionedArray
 Twocommonways:
– Rowmajororder(byrows)–usedinmostlanguages
– Columnmajororder(bycolumns)–usedinFortran

Compile-TimeDescriptors

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

AssociativeArrays
 Anassociativearrayisanunorderedcollectionofdataelementsthatareindexedbyanequalnumbero
fvaluescalledkeys
– 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"};

2.3 RecordTypes–CO2
 Arecordisapossiblyheterogeneousaggregateofdataelementsinwhichtheindividualelementsareident
ifiedbynames
 Designissues:
– Whatisthesyntacticformofreferencestothefield?
– Areellipticalreferencesallowed?
DefinitionofRecordsinCOBOL
 COBOLuseslevelnumberstoshownestedrecords;othersuserecursivedefinition
01EMP-REC.

PET ENGINEERING COLLEGE


02EMP-NAME.
05FIRSTPICX(20).
05MIDPICX(10).
05LASTPICX(20).
02HOURLY-RATEPIC99V99.

PET ENGINEERING COLLEGE


DefinitionofRecordsinAda
 Recordstructuresareindicatedinanorthogonalway
typeEmp_Rec_TypeisrecordF
irst:String(1..20);
Mid:String(1..10);
Last:String(1..20);Hourly_
Rate: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
 Ellipticalreferencesallowleavingoutrecordnamesaslongasthereferenceisunambiguous,forexam
pleinCOBOL
FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are
ellipticalreferencestotheemployee‘sfirstname
OperationsonRecords
 Assignmentisverycommonifthetypesareidentical
 Adaallowsrecordcomparison
 Adarecordscanbeinitializedwithaggregateliterals
 COBOLprovidesMOVECORRESPONDING
– Copiesafieldofthesourcerecordtothecorrespondingfieldinthetargetrecord
EvaluationandComparisontoArrays
 Recordsareusedwhencollectionofdatavaluesisheterogeneous
 Accesstoarrayelementsismuchslowerthanaccesstorecordfields,
becausesubscriptsaredynamic(fieldnamesarestatic)
 Dynamicsubscriptscouldbeusedwithrecordfieldaccess,butitwo
ulddisallowtypecheckinganditwouldbemuchslower

Figure3.7ImplementationofRecordType
UnionsTypes
 Aunionisatypewhosevariablesareallowedtostoredifferenttypevaluesatdifferenttimesduringexecuti
on
 Designissues
– Shouldtypecheckingberequired?
– Shouldunionsbeembeddedinrecords?

Discriminatedvs.FreeUnions
 Fortran,C,andC+
+provideunionconstructsinwhichthereisnolanguagesupportfortypechecking;theunioninthesela
nguagesiscalledfreeunion
 Typecheckingofunionsrequirethateachunionincludeatypeindicatorcalledadiscriminant

PET ENGINEERING COLLEGE


– SupportedbyAda

PET ENGINEERING COLLEGE


AdaUnionTypestypeSh AdaUnionTypeIllustrated
apeis(Circle,Triangle,Rectangle);typeCol
orsis(Red,Green,Blue);
typeFigure(Form:Shape)isrecordFilled
:Boolean;
Color:Colors;c
aseFormis
whenCircle=>Diameter:Float;
whenTriangle=>Leftside,Rightside:Intege
r;Angle:Float;
whenRectangle=>Side1,Side2:Integer;en
dcase; Figure3.8ADiscriminatedUnionofThr
endrecord;
eeShapeVariables
EvaluationofUnions
 Freeunionsareunsafe
– Donotallowtypechecking
 JavaandC#donotsupportunions
– Reflectiveofgrowingconcernsforsafetyinprogramminglanguage
 Ada‘sdescriminatedunionsaresafe

PointerandReferenceTypes
 Apointertypevariablehasarangeofvaluesthatconsistsofmemoryaddressesandaspecialvalue,nil
 Providethepowerofindirectaddressing
 Provideawaytomanagedynamicmemory
 Apointercanbeusedtoaccessalocationintheareawherestorageisdynamicallycreated(usuallycalle
daheap)
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

PET ENGINEERING COLLEGE


Figure3.9Theassignmentoperationj=*ptr

PET ENGINEERING COLLEGE


ProblemswithPointers
 Danglingpointers(dangerous)
– Apointerpointstoaheap-dynamicvariablethathasbeendeallocated
 Lostheap-dynamicvariable
– Anallocatedheap-
dynamicvariablethatisnolongeraccessibletotheuserprogram(oftencalledgarbage)
 Pointerp1issettopointtoanewlycreatedheap-dynamicvariable
 Pointerp1islatersettopointtoanothernewlycreatedheap-dynamicvariable
 Theprocessoflosingheap-dynamicvariablesiscalledmemoryleakage
PointersinAda
 Somedanglingpointersaredisallowedbecausedynamicobjectscanbeautomaticallydeallocatedatt
heendofpointer'stypescope
 Thelostheap-
dynamicvariableproblemisnoteliminatedbyAda(possiblewithUNCHECKED_DEALLOCATI
ON)
PointersinCandC++
 Extremelyflexiblebutmustbeusedwithcare
 Pointerscanpointatanyvariableregardlessofwhenorwhereitwasallocated
 Usedfordynamicstoragemanagementandaddressing
 Pointerarithmeticispossible
 Explicitdereferencingandaddress-ofoperators
 Domaintypeneednotbefixed(void*)
void*canpointtoanytypeandcanbetypechecked(cannotb
ede-referenced)
PointerArithmeticinCandC++
floatstuff[100];f
loat*p;
p=stuff;
*(p+5)isequivalenttostuff[5]andp[5]
*(p+i)isequivalenttostuff[i]andp[i]
ReferenceTypes
 C+
+includesaspecialkindofpointertypecalledareferencetypethatisusedprimarilyforformalparameters
– Advantagesofbothpass-by-referenceandpass-by-value
 JavaextendsC++‘sreferencevariablesandallowsthemtoreplacepointersentirely
– Referencesarereferencestoobjects,ratherthanbeingaddresses
 C#includesboththereferencesofJavaandthepointersofC++
EvaluationofPointers
 Danglingpointersanddanglingobjectsareproblemsasisheapmanagement
 Pointersarelikegoto's--theywidentherangeofcellsthatcanbeaccessedbyavariable
 Pointersorreferencesarenecessaryfordynamicdatastructures--
sowecan'tdesignalanguagewithoutthem
RepresentationsofPointers
 Largecomputersusesinglevalues
 Intelmicroprocessorsusesegmentandoffset

PET ENGINEERING COLLEGE


DanglingPointerProblem
 Tombstone:extraheapcellthatisapointertotheheap-dynamicvariable
– Theactualpointervariablepointsonlyattombstones
– Whenheap-dynamicvariablede-allocated,tombstoneremainsbutsettonil
– Costlyintimeandspace

PET ENGINEERING COLLEGE


 Locks-and-keys:Pointervaluesarerepresentedas(key,address)pairs
– Heap-dynamicvariablesarerepresentedasvariablepluscellforintegerlockvalue
– Whenheap-
dynamicvariableallocated,lockvalueiscreatedandplacedinlockcellandkeycellofpointer
HeapManagement
 Averycomplexrun-timeprocess
 Single-sizecellsvs.variable-sizecells
 Twoapproachestoreclaimgarbage
– Referencecounters(eagerapproach):reclamationisgradual
– Mark-sweep(lazyapproach):reclamationoccurswhenthelistofvariablespacebecomesempty
ReferenceCounter
 Referencecounters:maintainacounterineverycellthatstorethenumberofpointerscurrentlypointingatt
hecell
– Disadvantages:spacerequired,executiontimerequired,complicationsforcellsconnectedcircularl
y
– Advantage:itisintrinsicallyincremental,sosignificantdelaysintheapplicationexecutionareav
oided
Mark-Sweep
 Therun-
timesystemallocatesstoragecellsasrequestedanddisconnectspointersfromcellsasnecessary;mar
k-sweepthenbegins
– Everyheapcellhasanextrabitusedbycollectionalgorithm
– Allcellsinitiallysettogarbage
– Allpointerstracedintoheap,andreachablecellsmarkedasnotgarbage
– Allgarbagecellsreturnedtolistofavailablecells
– Disadvantages:initsoriginalform,itwasdonetooinfrequently.Whendone,itcausedsignificant
delaysinapplicationexecution.Contemporarymarksweepalgorithmsavoidthisbydoingitmor
eoften—calledincrementalmarksweep

Figure3.10MarkingAlgorithm

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

PET ENGINEERING COLLEGE


2.4 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.,IndexOutOfBoundsException)
– 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:
(name,address,value,type,lifetime,andscope)
 Name-notallvariableshavethem(anonymous)
 Address-thememoryaddresswithwhichitisassociated(alsocalledl-value)
– Avariablemayhavedifferentaddressesatdifferenttimesduringexecution
– Avariablemayhavedifferentaddressesatdifferentplacesinaprogram
– Iftwovariablenamescanbeusedtoaccessthesamememorylocation,theyarecalledaliases
– Aliasesareharmfultoreadability(programreadersmustrememberallofthem)
 Howaliasescanbecreated:
– Pointers,referencevariables,CandC++unions

PET ENGINEERING COLLEGE


– Someoftheoriginaljustificationsforaliasesarenolongervalid;e.g.,memoryreuseinFORTRA
N
– Replacethemwithdynamicallocation

PET ENGINEERING COLLEGE


 Type-
determinestherangeofvaluesofvariablesandthesetofoperationsthataredefinedforvaluesofthattype;in
thecaseoffloatingpoint,typealsodeterminesthePrecision
 Value-thecontentsofthelocationwithwhichthevariableisassociated
 Abstractmemorycell-thephysicalcellorcollectionofcellsassociatedwithavariable

TheConceptofBinding
 Thel-valueofavariableisitsaddress
 Ther-valueofavariableisitsvalue
 Def:Abindingisanassociation,suchasbetweenanattributeandanentity,orbetweenanoperationand
asymbol
 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:Abindingisstaticifitfirstoccursbeforeruntimeandremainsunchangedthroughoutprogramex
ecution.
 Def:Abindingisdynamicifitfirstoccursduringexecutionorcanchangeduringexecutionoftheprogram.
 TypeBindings
– Howisatypespecified?
– Whendoesthebindingtakeplace?
– Ifstatic,thetypemaybespecifiedbyeitheranexplicitoranimplicitdeclaration
 Def:Anexplicitdeclarationisaprogramstatementusedfordeclaringthetypesofvariables
 Def:Animplicitdeclarationisadefaultmechanismforspecifyingtypesofvariables(thefirstappearanceo
fthevariableintheprogram)
 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,typesaredeterminedfromthecontextofthereference
 StorageBindings&Lifetime

PET ENGINEERING COLLEGE


– Allocation-gettingacellfromsomepoolofavailablecells
– Deallocation-puttingacellbackintothepool

PET ENGINEERING COLLEGE


 Def:Thelifetimeofavariableisthetimeduringwhichitisboundtoaparticularmemorycell
 Categoriesofvariablesbylifetimes
– Static--
boundtomemorycellsbeforeexecutionbeginsandremainsboundtothesamememorycellthrou
ghoutexecution.
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

2.5 TypeChecking-CO3
 Generalizetheconceptofoperandsandoperatorstoincludesubprogramsandassignments
 Typecheckingistheactivityofensuringthattheoperandsofanoperatorareofcompatibletypes
 Acompatibletypeisonethatiseitherlegalfortheoperator,orisallowedunderlanguagerulestobeimplicitl
yconverted,bycompiler-generatedcode,toalegaltype.Thisautomaticconversioniscalledascoercion.
 Atypeerroristheapplicationofanoperatortoanoperandofaninappropriatetype
 Ifalltypebindingsarestatic,nearlyalltypecheckingcanbestatic
 Iftypebindingsaredynamic,typecheckingmustbedynamic
 Def:Aprogramminglanguageisstronglytypediftypeerrorsarealwaysdetected

PET ENGINEERING COLLEGE


TypeCompatibility

 Ourconcernisprimarilyforstructuredtypes
 Def:Nametypecompatibilitymeansthetwovariableshavecompatibletypesiftheyareineitherthesamed
eclarationorindeclarationsthatusethesametypename
 Easytoimplementbuthighlyrestrictive:
– Subrangesofintegertypesarenotcompatiblewithintegertypes
– Formalparametersmustbethesametypeastheircorrespondingactualparameters(Pascal)
 Structuretypecompatibilitymeansthattwovariableshavecompatibletypesiftheirtypeshaveidenticalst
ructures
 Moreflexible,buthardertoimplement
 Considertheproblemoftwostructuredtypes:
– Aretworecordtypescompatibleiftheyarestructurallythesamebutusedifferentfieldnames?
– Aretwoarraytypescompatibleiftheyarethesameexceptthatthesubscriptsaredifferent?
(e.g.,[1..10]and[0..9])
– Are two enumeration types compatible if their components are
spelleddifferently?
– Withstructuraltypecompatibility,youcannotdifferentiatebetweentypesofthesamestructure(e.g.,diffe
rentunitsofspeed,bothfloat)
 Languageexamples:
– Pascal:usuallystructure,butinsomecasesnameisused(formalparameters)
– C:structure,exceptforrecords
– Ada:restrictedformofname
o Derivedtypesallowtypeswiththesamestructuretobedifferent
o Anonymoustypesareallunique,evenin:
A,B:array(1..10)ofINTEGER:

2.6 StrongTyping–CO2

 Advantageofstrongtyping:allowsthedetectionofthemisusesofvariablesthatresultintypeerrors
 Languageexamples:
– FORTRAN77isnot:parameters,EQUIVALENCE
– Pascalisnot:variantrecords
– CandC++arenot:parametertypecheckingcanbeavoided;unionsarenottypechecked
– Adais,almost(UNCHECKEDCONVERSIONisloophole)
(Javaissimilar)
 Coercionrulesstronglyaffectstrongtyping--theycanweakenitconsiderably(C++versusAda)
 AlthoughJavahasjusthalftheassignmentcoercionsofC+
+,itsstrongtypingisstillfarlesseffectivethanthatofAda

PET ENGINEERING COLLEGE


NamedConstants
 Def:Anamedconstantisavariablethatisboundtoavalueonlywhenitisboundtostorage
 Advantages:readabilityandmodifiability
 Usedtoparameterizeprograms
 Thebindingofvaluestonamedconstantscanbeeitherstatic(calledmanifestconstants)ordynamic
 Languages:
– Pascal:literalsonly
– FORTRAN90:constant-valuedexpressions
– Ada,C++,andJava:expressionsofanykind

VariableInitialization
 Def:Thebindingofavariabletoavalueatthetimeitisboundtostorageiscalledinitialization
 Initializationisoftendoneonthedeclarationstatemente.g.,Javaintsum=0

Summary
 Thedatatypesofalanguagearealargepartofwhatdeterminesthatlanguage‘sstyleandusefulness
 Theprimitivedatatypesofmostimperativelanguagesincludenumeric,character,andBoolea
ntypes
 Theuser-
definedenumerationandsubrangetypesareconvenientandaddtothereadabilityandreliabilityofpro
grams
 Arraysandrecordsareincludedinmostlanguages
 Pointersareusedforaddressingflexibilityandtocontroldynamicstoragemanagement
 Casesensitivityandtherelationshipofnamestospecialwordsrepresentdesignissuesofnames
 Variablesarecharacterizedbythesextuples:name,address,value,type,lifetime,scope
 Bindingistheassociationofattributeswithprogramentities
 Scalarvariablesarecategorizedas:static,stackdynamic,explicitheapdynamic,implicit
heapdynamic
 Strongtypingmeansdetectingalltypeerrors

PET ENGINEERING COLLEGE


ExpressionsandStatements&ControlStructures

Introduction
 Expressions are the fundamental means of specifying computations in
aprogramminglanguage.
 Tounderstandexpressionevaluation,needtobefamiliarwiththeordersofoperatorandoperandevaluation.
 EssenceofimperativelanguagesisdominantroleofassignmentstatementsArithmeticExpressions.
 Arithmeticevaluationwasoneofthemotivationsforthedevelopmentofthefirstprogramminglanguages.

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

Typicalprecedencelevels:
 parentheses
 unaryoperators
 **(ifthelanguagesupportsit)
 *,/
 +,-
OperatorAssociativityRule
Theoperatorassociativityrulesforexpressionevaluationdefinetheorderinwhichadjacentoperatorswith
thesameprecedencelevelareevaluated.

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

PET ENGINEERING COLLEGE


ConditionalExpressions

PET ENGINEERING COLLEGE


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;sometimestheconstantisinthemachinelanguageinstru
ction.
 Parenthesizedexpressions:evaluatealloperandsandoperatorsfirst.
 Themostinterestingcaseiswhenanoperandisafunctioncall.

PotentialsforSideEffectsFunctionalsideeffects:whenafunctionchangesatwo-wayparameteroranon-
localvariable
Problemwithfunctionalsideeffects:Whenafunctionreferencedinanexpressionaltersanotheroperandoft
heexpression;
e.g.,foraparameterchange:
a=10;
/*assumethatfunchangesitsparameter*/
b=a+fun(a);
Twopossiblesolutionstothefunctionalsideeffectsproblem:Writethelanguagedefinitiontodisallowfunc
tionalsideeffects.
 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.

PET ENGINEERING COLLEGE


 Readabilitymaysuffer,evenwhentheoperatorsmakesense.

PET ENGINEERING COLLEGE


TypeConversions
Anarrowingconversionisonethatconvertsanobjecttoatypethatcannotincludeallofthevaluesoftheo
riginaltype.
e.g.,floattoint
Awideningconversionisoneinwhichanobjectisconvertedtoatypethatcanincludeatleastapproximations
toallofthevaluesoftheoriginaltype.
e.g.,inttofloat
MixedMode
Amixed-
modeexpressionisonethathasoperandsofdifferenttypesAcoercionisanimplicittypeco
nversion
Disadvantageofcoercions:
– Theydecreaseinthetypeerrordetectionabilityofthecompiler
 Inmostlanguages,allnumerictypesarecoercedinexpressions,usingwideningconversions.
 InAda,therearevirtuallynocoercionsinexpressionsExplicitTypeConve
rsionscalledascastinginC-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:
OperandsareBooleanandtheresultisBooleanExampleoperators
FORTRAN77 FORTRAN90 C Ada
.AND. and && and
.OR. or || or
.NOT. not ! not
xor --- --- ----
 NoBooleanTypeinC
 C89hasnoBooleantype--itusesinttypewith0forfalseandnonzerofortrue
 OneoddcharacteristicofC‘sexpressions:a<b<cisalegalexpression,buttheresultisnotwhatyoumi
ghtexpect:
 Leftoperatorisevaluated,producing0or1
 Theevaluationresultisthencomparedwiththethirdoperand(i.e.,c)

2.8 ShortCircuitEvaluation-CO3

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


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

2.9 AssignmentStatementsCO3

Thegeneralsyntax:<target_var><assign_operator><expression>Theassignment
operator
 ‘=’inFORTRAN,BASIC,theC-basedlanguages
 ‘:=’inALGOL,Pascal,Ada
–Equal‘=’canbebadwhenitisoverloadedfortherelationaloperatorforequality(that‘swhytheC-
basedlanguagesuse==astherelationaloperator)
ConditionalTargets(Perl)
($flag?$total:$subtotal)=0
Whichisequivalentto
if($flag)
{$total=0}else{$subt
otal=0}

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

UnaryAssignmentOperators
UnaryassignmentoperatorsinC-
basedlanguagescombineincrementanddecrementoperationswithassignment.Forexample
sum+=++count(countincremented,addedtosum)sum+=count++
(countincremented,addedtosum)count++(countincremented)
-count++(countincrementedthennegated)

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

PET ENGINEERING COLLEGE


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

2.10 ControlStructures-CO3
Acontrolstructureisacontrolstatementandthestatementswhoseexecutionitcontrols.

LevelsofControlFlow
 Withinexpressions
 Amongprogramunits
 Amongprogramstatements

ControlStatements:Evolution
 FORTRANIcontrolstatementswerebaseddirectlyonIBM704hardware
 Muchresearchandargumentinthe1960sabouttheissue
Oneimportantresult:Itwasproventhatallalgorithmsrepresentedbyflowchartscanbecodedwithonlytwo-
wayselectionandpretestlogicalloops

2.11 SelectionStatements–CO3
Aselectionstatementprovidesthemeansofchoosingbetweentwoormorepathsofexecution.Twogeneral
categories:
 Two-wayselectors
 Multiple-wayselectorsTwo-
WaySelectionStatementsGeneral
form as follows…
ifcontrol_expression
thenclause
elseclause
DesignIssues:
 Whatistheformandtypeofthecontrolexpression?
 Howarethethenandelseclausesspecified?
 Howshouldthemeaningofnestedselectorsbespecified?
TheControlExpression
 Ifthe‘then’reservedwordorsomeothersyntacticmarkerisnotusedtointroducethe‘then’clause,thecontr
olexpressionisplacedinparentheses.
 InC89,C99,Python,andC++,thecontrolexpressioncanbearithmetic.
 InlanguagessuchasAda,Java,Ruby,andC#,thecontrolexpressionmustbeBoolean.
ClauseForm
 Inmanycontemporarylanguages,thethenandelseclausescanbesinglestatementsorcompoundstateme
nts
 InPerl,allclausesmustbedelimitedbybraces(theymustbecompound)

PET ENGINEERING COLLEGE


 InFortran95,Ada,andRuby,clausesarestatementsequences
 Pythonusesindentationtodefineclauses

PET ENGINEERING COLLEGE


ifx>y:
x=y
print"case1"
NestingSelectors:Javaexample
if(sum==0)if
(count==0)r
esult=0;
elseresult=1;
 Whichifgetstheelse?
 Java'sstaticsemanticsrule:elsematcheswiththenearestifNestingSelectors
 Toforceanalternativesemantics,compoundstatementsmaybeused:
if(sum==0)
{if(count==0
)result=0;}el
seresult=1;
 TheabovesolutionisusedinC,C++,andC#
 Perlrequiresthatallthenandelseclausestobecompound
 Statementsequencesasclauses:Ruby
ifsum==0thenifc
ount==0thenres
ult=0
elseresul
t=1end
end
-Python
ifsum==0:
ifcount==0:
result=0el
se:
result=1

Multiple-WaySelectionStatements
AllowtheselectionofoneofanynumberofstatementsorstatementgroupsDesignIssues:
 Whatistheformandtypeofthecontrolexpression?
 Howaretheselectablesegmentsspecified?
 Isexecutionflowthroughthestructurerestrictedtoincludejustasingleselectablesegment?
 Howarecasevaluesspecified?
 Whatisdoneaboutunrepresentedexpressionvalues?

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

caseconst_expr_n:stmt_n;
[default:stmt_n+1]}
 DesignchoicesforC‘sswitchstatement

PET ENGINEERING COLLEGE


 Controlexpressioncanbeonlyanintegertype
 Selectable segments can be statement sequences, blocks, or
compoundstatements
 Anynumberofsegmentscanbeexecutedinoneexecutionoftheconstruct(thereisnoimplicitbranchatthe
endofselectablesegments)

PET ENGINEERING COLLEGE


 defaultclauseisforunrepresentedvalues(ifthereisnodefault,thewholestatementdoesnothing)
 C#
– DiffersfromCinthatithasastaticsemanticsrulethatdisallowstheimplicitexecutionofmorethan
onesegment
– Eachselectablesegmentmustendwithanunconditionalbranch(gotoorbreak)
 Ada
caseexpressionis
whenchoicelist=>stmt_sequence;

whenchoicelist=>stmt_sequence
;whenothers=>stmt_sequence;]
endcase;
MorereliablethanC‘sswitch(onceastmt_sequenceexecutioniscompleted,controlispassedtothefirststatem
entafterthecasestatement
 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=True
elsifcount<100:
bag2=Trueel
seifcount<1000:
bag3=True

IterativeStatements
 Therepeatedexecutionofastatementorcompoundstatementisaccomplishedeitherbyiterationorrecurs
ion
 Generaldesignissuesforiterationcontrolstatements:
1. Howisiterationcontrolled?
2. Whereisthecontrolmechanismintheloop?
Counter-ControlledLoops
Acountingiterativestatementhasaloopvariable,andameansofspecifyingtheinitialandterminal,and
stepsizevalues
DesignIssues:
 Whatarethetypeandscopeoftheloopvariable?

PET ENGINEERING COLLEGE


 Whatisthevalueoftheloopvariableatlooptermination?
 Shoulditbelegalfortheloopvariableorloopparameterstobechangedintheloopbody,andifso,doesthech
angeaffectloopcontrol?
 Shouldtheloopparametersbeevaluatedonlyonce,oronceforeveryiteration?

PET ENGINEERING COLLEGE


IterativeStatements:Examples
FORTRAN95syntax
DOlabelvar=start,finish[,stepsize]Stepsizeca
nbeanyvaluebutzeroParameterscanbeexpression
s
Designchoices:
1. LoopvariablemustbeINTEGER
2. Loopvariablealwayshasitslastvalue
3. Theloopvariablecannotbechangedintheloop,buttheparameterscan;becausetheyareevaluatedonlyonce,it
doesnotaffectloopcontrol
4. Loopparametersareevaluatedonlyonce
 FORTRAN95:asecondform:
[name:]Dovariable=initial,terminal[,stepsize]

EndDo[name]
– CannotbranchintoeitherofFortran‘sDostatements
 Ada
forvarin[reverse]discrete_rangeloop...endloop
 Designchoices:
– Typeoftheloopvariableisthatofthediscreterange(Adiscreterangeisasub-
rangeofanintegerorenumerationtype).
– Loopvariabledoesnotexistoutsidetheloop
– Theloopvariablecannotbechangedintheloop,butthediscreterangecan;itdoesnotaffectloopcontrol
– Thediscreterangeisevaluatedjustonce
– Cannotbranchintotheloopbody
 C-basedlanguages
for([expr_1];[expr_2];[expr_3])statement
– Theexpressionscanbewholestatements,orevenstatementsequences,withthestatementssepara
tedbycommas
– Thevalueofamultiple-statementexpressionisthevalueofthelaststatementintheexpression
– Ifthesecondexpressionisabsent,itisaninfiniteloop
 Designchoices:
– Thereisnoexplicitloopvariable
– Everythingcanbechangedintheloop
– Thefirstexpressionisevaluatedonce,buttheothertwoareevaluatedwitheachiteration
 C++differsfromCintwoways:
– ThecontrolexpressioncanalsobeBoolean
– Theinitialexpressioncanincludevariabledefinitions(scopeisfromthedefinitiontotheendoftheloop
body)
 JavaandC#
– DiffersfromC++inthatthecontrolexpressionmustbeBoolean
– IterativeStatements:Logically-ControlledLoops
– RepetitioncontrolisbasedonaBooleanexpression
 Designissues:
– Pretestorposttest?

PET ENGINEERING COLLEGE


– Shouldthelogicallycontrolledloopbeaspecialcaseofthecountingloopstatementoraseparatest
atement?

PET ENGINEERING COLLEGE


 IterativeStatements:Logically-ControlledLoops:Examples
CandC++havebothpretestandposttestforms,inwhichthecontrolexpressioncanbearithmetic:
while(ctrl_expr)doloo
pbodyloopbodywhile(
ctrl_expr)
 JavaislikeCandC+
+,exceptthecontrolexpressionmustbeBoolean(andthebodycanonlybeenteredatthebeginning--
Javahasnogoto
 IterativeStatements:Logically-ControlledLoops:Examples
 Adahasapretestversion,butnoposttest
 FORTRAN95hasneither
 PerlandRubyhavetwopretestlogicalloops,whileanduntil.Perlalsohastwoposttestloops

UnconditionalBranching:User-LocatedLoopControlMechanisms
 Sometimesitisconvenientfortheprogrammerstodecidealocationforloopcontrol(otherthantoporbotto
moftheloop)
 Simpledesignforsingleloops(e.g.,break)
 Designissuesfornestedloops
– Shouldtheconditionalbepartoftheexit?
– Shouldcontrolbetransferableoutofmorethanoneloop?User-
LocatedLoopControlMechanismsbreakandcontinue
 C,C++,Python,Ruby,andC#haveunconditionalunlabeledexits(break)
 JavaandPerlhaveunconditionallabeledexits(breakinJava,lastinPerl)
 C,C+
+,andPythonhaveanunlabeledcontrolstatement,continue,thatskipstheremainderofthecurrentite
ration,butdoesnotexittheloop
 JavaandPerlhavelabeledversionsofcontinue
IterativeStatements:IterationBasedonDataStructures
 Numberofelementsofinadatastructurecontrolloopiteration
 Controlmechanismisacalltoaniteratorfunctionthatreturnsthenextelementinsomechosenorder,ifther
eisone;elseloopisterminate
 C'sforcanbeusedtobuildauser-definediterator:
for(p=root;p==NULL;traverse(
p)){}
 C#‘sforeachstatementiteratesontheelementsofarraysandothercollections:
Strings[]=strList={"Bob","Carol","Ted"};fore
ach(StringsnameinstrList)Console.WriteLine("
Name:{0}",name);
Thenotation{0}indicatesthepositioninthestringtobedisplayed
 Perlhasabuilt-initeratorforarraysandhashes,foreachUnconditionalBranching
 Transfersexecutioncontroltoaspecifiedplaceintheprogram
 Representedoneofthemostheateddebatesin1960‘sand1970‘s
 Well-knownmechanism:gotostatement
 Majorconcern:Readability
 Somelanguagesdonotsupportgotostatement(e.g.,Java)

PET ENGINEERING COLLEGE


 C#offersgotostatement(canbeusedinswitchstatements)
 Loopexitstatementsarerestrictedandsomewhatcamouflagedgoto‘s

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


 Varietyofstatement-levelstructures
 Choiceofcontrolstatementsbeyondselectionandlogicalpretestloopsisatrade-
offbetweenlanguagesizeandwritability
 Functional and logic programming languages are quite different
controlstructures

PET ENGINEERING COLLEGE


UNIT-3
SubprogramsandBlocks

Introduction
 Twofundamentalabstractionfacilities
– Processabstraction
 Emphasizedfromearlydays
– Dataabstraction
 Emphasizedinthe1980s

3.1 FundamentalsofSubprograms–CO4
 Eachsubprogramhasasingleentrypoint
 Thecallingprogramissuspendedduringexecutionofthecalledsubprogram
 Controlalwaysreturnstothecallerwhenthecalledsubprogram‘sexecutionterminates
BasicDefinitions
 Asubprogramdefinitiondescribestheinterfacetoandtheactionsofthesubprogramabstraction
 Asubprogramcallisanexplicitrequestthatthesubprogrambeexecuted
 Asubprogramheaderisthefirstpartofthedefinition,includingthename,thekindofsubprogram,and
theformalparameters
 Theparameterprofile(akasignature)ofasubprogramisthenumber,order,andtypesofitsparameters
 Theprotocolisasubprogram‘sparameterprofileand,ifitisafunction,itsreturntype
 FunctiondeclarationsinCandC++areoftencalledprototypes
 Asubprogramdeclarationprovidestheprotocol,butnotthebody,ofthesubprogram
 Aformalparameterisadummyvariablelistedinthesubprogramheaderandusedinthesubprogram
 Anactualparameterrepresentsavalueoraddressusedinthesubprogramcallstatement
Actual/FormalParameterCorrespondence
 Positional
– Thebindingofactualparameterstoformalparametersisbyposition:thefirstactualparameterisbound
tothefirstformalparameterandsoforth
– Safeandeffective
 Keyword
– Thenameoftheformalparametertowhichanactualparameteristobeboundisspecifiedwiththeactual
parameter
– Parameterscanappearinanyorder
FormalParameterDefaultValues
 Incertainlanguages(e.g.,C+
+,Ada),formalparameterscanhavedefaultvalues(ifnotactualparameterispassed)
– InC++,defaultparametersmustappearlastbecauseparametersarepositionallyassociated
 C#methodscanacceptavariablenumberofparametersaslongastheyareofthesametype

PET ENGINEERING COLLEGE


ProceduresandFunctions
 Therearetwocategoriesofsubprograms
– Procedures are collection of statements that define
parameterizedcomputations
– Functionsstructurallyresembleproceduresbutaresemanticallymodeledonmathematicalfunc
tions
 Theyareexpectedtoproducenosideeffects
 Inpractice,programfunctionshavesideeffects

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

ScopeandLifetime
 Thescopeofavariableistherangeofstatementsoverwhichitisvisible
 Thenonlocalvariablesofaprogramunitarethosethatarevisiblebutnotdeclaredthere
 Thescoperulesofalanguagedeterminehowreferencestonamesareassociatedwithvariables
 Scopeandlifetimearesometimescloselyrelated,butaredifferentconcepts
 ConsiderastaticvariableinaCorC++function
Staticscope
– Basedonprogramtext
– Toconnectanamereferencetoavariable,you(orthecompiler)mustfindthedeclaration
– Searchprocess:searchdeclarations,firstlocally,theninincreasinglylargerenclosingscopes,unt
iloneisfoundforthegivenname
– Enclosingstaticscopes(toaspecificscope)arecalleditsstaticancestors;theneareststaticancesto
riscalledastaticparent
 Variablescanbehiddenfromaunitbyhavinga"closer"variablewiththesamename
 C++andAdaallowaccesstothese"hidden"variables
– InAda:unit.name
– InC++:class_name::name
 Blocks
– Amethodofcreatingstaticscopesinsideprogramunits--fromALGOL60
– Examples:
CandC++:for(...)
{intindex;
...
}
Ada:declareLCL:FLOAT;be
gin
...
end

PET ENGINEERING COLLEGE


 EvaluationofStaticScoping
 Considertheexample:
AssumeMAINcallsAandB

PET ENGINEERING COLLEGE


AcallsCandD
BcallsAandE
 SupposethespecischangedsothatDmustnowaccesssomedatainB
 Solutions:
– PutDinB(butthenCcannolongercallitandDcannotaccessA'svariables)
– MovethedatafromBthatDneedstoMAIN(butthenallprocedurescanaccessthem)
 Sameproblemforprocedureaccess
 Overall:staticscopingoftenencouragesmanyglobals
DynamicScope
– Basedoncallingsequencesofprogramunits,nottheirtextuallayout(temporalversusspatial)
– Referencestovariablesareconnectedtodeclarationsbysearchingbackthroughthechainofsubp
rogramcallsthatforcedexecutiontothispoint

ScopeExample
MAIN
-
declarationof
xSUB1
-declarationofx-
...
callSUB2
...S
UB2
...
-referencetox-
...
...
callSUB1

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

LocalReferencingEnvironments
 Def:Thereferencingenvironmentofastatementisthecollectionofallnamesthatarevisibleinthestateme
nt
 Inastatic-
scopedlanguage,itisthelocalvariablesplusallofthevisiblevariablesinalloftheenclosingscopes
 Asubprogramisactiveifitsexecutionhasbegunbuthasnotyetterminated
 Inadynamic-
scopedlanguage,thereferencingenvironmentisthelocalvariablesplusallvisiblevariablesinallacti
vesubprograms

PET ENGINEERING COLLEGE


 Localvariablescanbestack-dynamic(boundtostorage)
– Advantages
 Supportforrecursion
 Storageforlocalsissharedamongsomesubprograms
– Disadvantages
 Allocation/de-allocation,initializationtime

PET ENGINEERING COLLEGE


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

3.3 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(enforcingwriteprotectioni
snoteasy)
– Whencopiesareused,additionalstorageisrequired
– Storageandcopyoperationscanbecostly

Pass-by-Result(OutMode)
 Whenaparameterispassedbyresult,novalueistransmittedtothesubprogram;thecorrespondingformal
parameteractsasalocalvariable;itsvalueistransmittedtocaller‘sactualparameterwhencontrolisreturn
edtothecaller
– Requireextrastoragelocationandcopyoperation
 Potentialproblem:sub(p1,p1);whicheverformalparameteriscopiedbackwillrepresentthecurrentvalu
eofp1
Pass-by-Value-Result(InoutMode)
 Acombinationofpass-by-valueandpass-by-result
 Sometimescalledpass-by-copy

PET ENGINEERING COLLEGE


 Formalparametershavelocalstorage
 Disadvantages:
– Thoseofpass-by-result
– Thoseofpass-by-value

PET ENGINEERING COLLEGE


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,butactualbindingtoavalueoraddresstake
splaceatthetimeofareferenceorassignment
 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;inisthedefaultmode
– Formalparametersdeclaredoutcanbeassignedbutnotreferenced;thosedeclaredincanbereferenced
butnotassigned;inoutparameterscanbereferencedandassigned
 C#
– Defaultmethod:pass-by-value
– Pass-by-referenceisspecifiedbyprecedingbothaformalparameteranditsactualparameterwithref
 PHP:verysimilartoC#
 Perl:allactualparametersareimplicitlyplacedinapredefinedarraynamed@_
TypeCheckingParameters
 Consideredveryimportantforreliability
 FORTRAN77andoriginalC:none
 Pascal,FORTRAN90,Java,andAda:itisalwaysrequired

PET ENGINEERING COLLEGE


 ANSICandC++:choiceismadebytheuser
– Prototypes
 RelativelynewlanguagesPerl,JavaScript,andPHPdonotrequiretypechecking
MultidimensionalArraysasParameters
 Ifamultidimensionalarrayispassedtoasubprogramandthesubprogramisseparatelycompiled,thec
ompilerneedstoknowthedeclaredsizeofthatarraytobuildthestoragemappingfunction
MultidimensionalArraysasParameters:CandC++
 Programmerisrequiredtoincludethedeclaredsizesofallbutthefirstsubscriptintheactualparameter
 Disallowswritingflexiblesubprograms
 Solution:passapointertothearrayandthesizesofthedimensionsasotherparameters;theusermustinclud
ethestoragemappingfunctionintermsofthesizeparameters
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#)thatissettothelengthofthearraywh
enthearrayobjectiscreated

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

3.4 ParametersSubprogramsasparameters–CO3
 Itissometimesconvenienttopasssubprogramnamesasparameters
 Issues:
– Areparametertypeschecked?
– Whatisthecorrectreferencingenvironmentforasubprogramthatwassentasaparameter?
ParametersthatareSubprogramNames:ParameterTypeChecking
 CandC+
+:functionscannotbepassedasparametersbutpointerstofunctionscanbepassed;parameterscanbetype
checked

PET ENGINEERING COLLEGE


 FORTRAN95typechecks

PET ENGINEERING COLLEGE


 LaterversionsofPascaland
 Adadoesnotallowsubprogramparameters;asimilaralternativeisprovidedviaAda‘sgenericfacility
ParametersthatareSubprogramNames:ReferencingEnvironment
 Shallowbinding:Theenvironmentofthecallstatementthatenactsthepassedsubprogram
 Deepbinding:Theenvironmentofthedefinitionofthepassedsubprogram
 Adhocbinding:Theenvironmentofthecallstatementthatpassedthesubprogram
3.5 OverloadedSubprograms–CO3
 Anoverloadedsubprogramisonethathasthesamenameasanothersubprograminthesamereferenci
ngenvironment
– Everyversionofanoverloadedsubprogramhasauniqueprotocol
 C++,Java,C#,andAdaincludepredefinedoverloadedsubprograms
 InAda,thereturntypeofanoverloadedfunctioncanbeusedtodisambiguatecalls(thustwooverloade
dfunctionscanhavethesameparameters)
 Ada,Java,C++,andC#allowuserstowritemultipleversionsofsubprogramswiththesamename
3.6 GenericSubprograms–CO3
 Agenericorpolymorphicsubprogramtakesparametersofdifferenttypesondifferentactivations
 Overloadedsubprogramsprovideadhocpolymorphism
 Asubprogramthattakesagenericparameterthatisusedinatypeexpressionthatdescribesthetypeoft
heparametersofthesubprogramprovidesparametricpolymorphism
Examplesofparametricpolymorphism:C++
template<classType>
Typemax(Typefirst,Typesecond)
{returnfirst>second?first:second;
}
 Theabovetemplatecanbeinstantiatedforanytypeforwhichoperator>isdefined
intmax(intfirst,intsecond)
{returnfirst>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):returnIntegeri
sSum:Integer:=0;
begin
forIndexinA‘rangeloop
Sum:=Sum+A(Index)*B(Index)en

PET ENGINEERING COLLEGE


dloop

PET ENGINEERING COLLEGE


returnsum;
end“*”;

c=a*b;--a,b,andcareoftypeVec_Type
3.7 Co-Routines–CO3
 Acoroutineisasubprogramthathasmultipleentriesandcontrolsthemitself
 Alsocalledsymmetriccontrol:callerandcalledcoroutinesareonamoreequalbasis
 Acoroutinecallisnamedaresume
 Thefirstresumeofacoroutineistoitsbeginning,butsubsequentcallsenteratthepointjustafterthelast
executedstatementinthecoroutine
 Coroutinesrepeatedlyresumeeachother,possiblyforever
 Coroutinesprovidequasi-
concurrentexecutionofprogramunits(thecoroutines);theirexecutionisinterleaved,butnotoverlapped

Figure5.2PossibleExecutionControls Figure5.3PossibleExecutionControls

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

PET ENGINEERING COLLEGE


 Somelanguagesallowoperatoroverloading
 Subprogramscanbegeneric
 Aco-routineisaspecialsubprogramwithmultipleentries

PET ENGINEERING COLLEGE


UNIT-4
AbstractDataTypes

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

4.2 IntroductiontoDataAbstraction–CO3
 AnAbstractDataTypeisauser-defineddatatypethatsatisfiesthefollowingtwoconditions:
– Therepresentationof,andoperationson,objectsofthetypearedefinedinasinglesyntacticunit
– Therepresentationofobjectsofthetypeishiddenfromtheprogramunitsthatusetheseobjects,sotheo
nlyoperationspossiblearethoseprovidedinthetype'sdefinition

AdvantagesofDataAbstraction
 Advantageofthefirstcondition
– Programorganization,modifiability(everythingassociatedwithadatastructureistogether),an
dseparatecompilation
 Advantagethesecondcondition
– Reliability--
byhidingthedatarepresentations,usercodecannotdirectlyaccessobjectsofthetypeordependonther
epresentation,allowingtherepresentationtobechangedwithoutaffectingusercode
LanguageRequirementsforADTs:
 Asyntacticunitinwhichtoencapsulatethetypedefinition
 Amethodofmakingtypenamesandsubprogramheadersvisibletoclients,whilehidingactualdefinitions
 SomeprimitiveoperationsmustbebuiltintothelanguageprocessorDesignIssues:
 Canabstracttypesbeparameterized?
 Whataccesscontrolsareprovided?

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

PET ENGINEERING COLLEGE


– Therepresentationoftheabstracttypeappearsinapartofthespecificationcalledtheprivatepart
 Morerestrictedformwithlimitedprivatetypes
– Privatetypeshavebuilt-inoperationsforassignmentandcomparison
– LimitedprivatetypeshaveNObuilt-inoperations
 Reasonsforthepublic/privatespecpackage:
1. Thecompilermustbeabletoseetherepresentationafterseeingonlythespecpackage(itcannotsee
theprivatepart)
2. Clientsmustseethetypename,butnottherepresentation(theyalsocannotseetheprivatepart)
 Havingpartoftheimplementationdetails(therepresentation)inthespecpackageandpart(themethodbo
dies)inthebodypackageisnotgood

Onesolution:makeallADTspointers
Problemswiththis:
1. Difficultieswithpointers
2. Objectcomparisons
3. ControlofobjectallocationislostAnExam
pleinAda
packageStack_Packis
typestack_typeislimitedprivate;max_size:cons
tant:=100;
functionempty(stk:instack_type)returnBoolean;procedurepush(stk:i
noutstack_type;elem:inInteger);procedurepop(stk:inoutstack_type);
functiontop(stk:instack_type)returnInteger;private--
hiddenfromclients
typelist_typeisarray(1..max_size)ofInteger;typestack_ty
peisrecord
list:list_type;
topsub:Integerrange0..max_size):=0;endreco
rd;
endStack_Pack

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

PET ENGINEERING COLLEGE


– Implicitlycalledwhenaninstanceiscreated
– Canbeexplicitlycalled

PET ENGINEERING COLLEGE


– Nameisthesameastheclassname
 Destructors
– Functionstocleanupafteraninstanceisdestroyed;usuallyjusttoreclaimheapstorage
– Implicitlycalledwhentheobject‘slifetimeends
– Canbeexplicitlycalled
– Nameistheclassname,precededbyatilde(~)AnExamplein
C++
classstack{
private:
int*stackPtr,maxLen,topPtr;
public:
stack(){//
aconstructorstackPtr=ne
wint[100];maxLen=99;
topPtr=-1;
};
~stack()
{delete[]stackPtr;};voidpus
h(intnum){…};voidpop()
{…};
inttop(){…};
intempty(){…};
}
EvaluationofADTsinC++andAda
 C++supportforADTsissimilartoexpressivepowerofAda
 Bothprovideeffectivemechanismsforencapsulationandinformationhiding
 Adapackagesaremoregeneralencapsulations;classesaretypes
 Friendfunctionsorclasses-toprovideaccesstoprivatememberstosomeunrelatedunitsorfunctions
– NecessaryinC++
LanguageExamples:Java
 SimilartoC++,except:
– Alluser-definedtypesareclasses
– Allobjectsareallocatedfromtheheapandaccessedthroughreferencevariables
– Individualentitiesinclasseshaveaccesscontrolmodifiers(privateorpublic),ratherthanclauses
– Javahasasecondscopingmechanism,packagescope,whichcanbeusedinplaceoffriends
 Allentitiesinallclassesinapackagethatdonothaveaccesscontrolmodifiersarevisiblethroughoutth
epackage
AnExampleinJava
classStackClass{pri
vate:
privateint[]*stackRef;
privateint[]maxLen,topIndex;public
StackClass(){//aconstructor
stackRef=newint[100];
maxLen=99;
topPtr=-1;
};

PET ENGINEERING COLLEGE


public void push (intnum)
{…};public void pop () {…};
publicinttop(){…};
publicbooleanempty(){…};
}

PET ENGINEERING COLLEGE


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

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

4.4 ParameterizedAbstractDataTypes-CO4
 ParameterizedADTsallowdesigninganADTthatcanstoreanytypeelements(amongotherthings)
 Alsoknownasgenericclasses
 C++,Ada,Java5.0,andC#2005providesupportforparameterizedADTs
ParameterizedADTsinAda
 AdaGenericPackages
– Makethestacktypemoreflexiblebymakingtheelementtypeandthesizeofthestackgeneric
generic
Max_Size:Positive;
typeElem_Typeisprivate;pack
ageGeneric_Stackis
TypeStack_Typeislimitedprivate;
functionTop(Stk:inoutStackType)returnElem_type;

endGeneric_Stack;

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


stack(intsize)
{stk_ptr=newint[size];
max_len=size-1;
top=-1;
};

}
stackstk(100);
 Thestackelementtypecanbeparameterizedbymakingtheclassatemplatedclass
template<classType>c
lassstack{
private:
Type*stackPtr;con
stintmaxLen;inttop
Ptr;
public:
stack(){
stackPtr=newType[100];
maxLen=99;
topPtr=-1;
}

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

4.5 Object-OrientedProgramming–CO4
 Abstractdatatypes
 Inheritance
– InheritanceisthecentralthemeinOOPandlanguagesthatsupportit
 Polymorphism
Inheritance

PET ENGINEERING COLLEGE


 Productivityincreasescancomefromreuse
– ADTsaredifficulttoreuse—alwaysneedchanges
– AllADTsareindependentandatthesamelevel
 Inheritanceallowsnewclassesdefinedintermsofexistingones,i.e.,byallowingthemtoinheritcommonp
arts

PET ENGINEERING COLLEGE


 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)objectsoftheclassando
bjectsofanyofitsdescendants
 Whenaclasshierarchyincludesclassesthatoverridemethodsandsuchmethodsarecalledthroughapoly
morphicvariable,thebindingtothecorrectmethodwillbedynamic
 Allowssoftwaresystemstobemoreeasilyextendedduringbothdevelopmentandmaintenance
DynamicBindingConcepts
 Anabstractmethodisonethatdoesnotincludeadefinition(itonlydefinesaprotocol)
 Anabstractclassisonethatincludesatleastonevirtualmethod
 Anabstractclasscannotbeinstantiated

4.6 DesignIssuesforOOPLanguages–CO4
 TheExclusivityofObjects
 AreSubclassesSubtypes?

PET ENGINEERING COLLEGE


 TypeCheckingandPolymorphism
 SingleandMultipleInheritance
 ObjectAllocationandDeAllocation

PET ENGINEERING COLLEGE


 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,thenobjectsofthederivedclassmustbehavethesameastheparentclassobject
 Aderivedclassisasubtypeifithasanis-arelationshipwithitsparentclass
– Subclasscanonlyaddvariablesandmethodsandoverrideinheritedmethodsin
“compatible”ways
TypeCheckingandPolymorphism
 Polymorphismmayrequiredynamictypecheckingofparametersandthereturnvalue
– Dynamictypecheckingiscostlyanddelayserrordetection
 Ifoverridingmethodsarerestrictedtohavingthesameparametertypesandreturntype,thecheckingcanbe
static
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

PET ENGINEERING COLLEGE


 Allowtheusertospecify

PET ENGINEERING COLLEGE


NestedClasses
 Ifanewclassisneededbyonlyoneclass,thereisnoreasontodefinesoitcanbeseenbyotherclasses
– Canthenewclassbenestedinsidetheclassthatusesit?
– Insomecases,thenewclassisnestedinsideasubprogramratherthandirectlyinanotherclass
 Otherissues:
– Whichfacilitiesofthenestingclassshouldbevisibletothenestedclassandviceversa

4.6 SupportforOOPinSmalltalk–CO4
 SmalltalkisapureOOPlanguage
– Everythingisanobject
– Allobjectshavelocalmemory
– Allcomputationisthroughobjectssendingmessagestoobjects
– Noneoftheappearancesofimperativelanguages
– Allobjectedareallocatedfromtheheap
– Alldeallocationisimplicit
 TypeCheckingandPolymorphism
– Allbindingofmessagestomethodsisdynamic
 Theprocessistosearchtheobjecttowhichthemessageissentforthemethod;ifnotfound,searchthesu
perclass,etc.uptothesystemclasswhichhasnosuperclass
– TheonlytypecheckinginSmalltalkisdynamicandtheonlytypeerroroccurswhenamessageisse
nttoanobjectthathasnomatchingmethod
 Inheritance
– ASmalltalksubclassinheritsalloftheinstancevariables,instancemethods,andclassmethodsofi
tssuperclass
– Allsubclassesaresubtypes(nothingcanbehidden)
– Allinheritanceisimplementationinheritance
– Nomultipleinheritance
 EvaluationofSmalltalk
– Thesyntaxofthelanguageissimpleandregular
– Goodexampleofpowerprovidedbyasmalllanguage
– Slowcomparedwithconventionalcompiledimperativelanguages
– Dynamicbindingallowstypeerrorstogoundetecteduntilruntime
– Introducedthegraphicaluserinterface
– Greatestimpact:advancementofOOP

4.7 SupportforOOPinC++-CO4
 GeneralCharacteristics:
– EvolvedfromCandSIMULA67
– AmongthemostwidelyusedOOPlanguages
– Mixedtypingsystem
– Constructorsanddestructors
– Elaborateaccesscontrolstoclassentities
 Inheritance
– Aclassneednotbethesubclassofanyclass

PET ENGINEERING COLLEGE


– Accesscontrolsformembersare
– Private(visibleonlyintheclassandfriends)(disallowssubclassesfrombeingsubtypes)

PET ENGINEERING COLLEGE


– Public(visibleinsubclassesandclients)
– Protected(visibleintheclassandinsubclasses,butnotclients)
 Inaddition,thesubclassingprocesscanbedeclaredwithaccesscontrols(privateorpublic),whichdef
inepotentialchangesinaccessbysubclasses
– Privatederivation-inheritedpublicandprotectedmembersareprivateinthesubclasses
– Public derivation public and protected members are also public
andprotectedinsubclasses
InheritanceExampleinC++
classbase_class{pri
vate:
inta;floa
tx;
protected:
intb;flo
aty;publ
ic:intc;f
loatz;
};
classsubclass_1:publicbase_class{…};
//Inthisone,bandyareprotectedand
//candzarepublic
classsubclass_2:privatebase_class{…};
//Inthisone,b,y,c,andzareprivate,
//andnoderivedclasshasaccesstoany
//memberofbase_class
 Amemberthatisnotaccessibleinasubclass(becauseofprivatederivation)canbedeclaredtobevisiblethe
reusingthescoperesolutionoperator(::),e.g.,
classsubclass_3:privatebase_class{ba
se_class::c;

}
 Onemotivationforusingprivatederivation
– Aclassprovidesmembersthatmustbevisible,sotheyaredefinedtobepublicmembers;aderivedclass
addssomenewmembers,butdoesnotwantitsclientstoseethemembersoftheparentclass,eventhoug
htheyhadtobepublicintheparentclassdefinition
 Multipleinheritanceissupported
– Iftherearetwoinheritedmemberswiththesamename,theycanbothbereferencedusingthescopereso
lutionoperator
 DynamicBinding
– Amethodcanbedefinedtobevirtual,whichmeansthattheycanbecalledthroughpolymorphicva
riablesanddynamicallyboundtomessages
– Apurevirtualfunctionhasnodefinitionatall
– Aclassthathasatleastonepurevirtualfunctionisanabstractclass
 Evaluation
– C++providesextensiveaccesscontrols(unlikeSmalltalk)
– C++providesmultipleinheritance
– InC+

PET ENGINEERING COLLEGE


+,theprogrammermustdecideatdesigntimewhichmethodswillbestaticallyboundandwhichm
ustbedynamicallybound
 Staticbindingisfaster!
– Smalltalktypecheckingisdynamic(flexible,butsomewhatunsafe)
– Becauseofinterpretationanddynamicbinding,Smalltalkis~10timesslowerthanC++

PET ENGINEERING COLLEGE


4.8 SupportforOOPinJava–CO4
 BecauseofitscloserelationshiptoC++,focusisonthedifferencesfromthatlanguage
 GeneralCharacteristics
– Alldataareobjectsexcepttheprimitivetypes
– Allprimitivetypeshavewrapperclassesthatstoreonedatavalue
– Allobjectsareheap-
dynamic,arereferencedthroughreferencevariables,andmostareallocatedwithnew
– Afinalizemethodisimplicitlycalledwhenthegarbagecollectorisabouttoreclaimthestorageoccupie
dbytheobject
 Inheritance
– Singleinheritancesupportedonly,butthereisanabstractclasscategorythatprovidessomeoftheb
enefitsofmultipleinheritance(interface)
– Aninterfacecanincludeonlymethoddeclarationsandnamedconstants,
e.g.,
publicinterfaceComparable{
publicintcomparedTo(Objectb);}
– Methodscanbefinal(cannotbeoverriden)
 DynamicBinding
– InJava,allmessagesaredynamicallyboundtomethods,unlessthemethodisfinal(i.e.,itcannotbe
overriden,thereforedynamicbindingservesnopurpose)
– Staticbindingisalsousedifthemethodsisstaticorprivatebothofwhichdisallowoverriding
 Severalvarietiesofnestedclasses
 Allarehiddenfromallclassesintheirpackage,exceptforthenestingclass
 Nestedclassescanbeanonymous
 Alocalnestedclassisdefinedinamethodofitsnestingclass
– Noaccessspecifierisused
 Evaluation
– DesigndecisionstosupportOOParesimilartoC++
– Nosupportforproceduralprogramming
– Noparentlessclasses
– Dynamicbindingisusedas“normal”waytobindmethodcallstomethoddefinitions
– Usesinterfacestoprovideasimpleformofsupportformultipleinheritance

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

PET ENGINEERING COLLEGE


 Dynamicbinding
– Toallowdynamicbindingofmethodcallstomethods:

PET ENGINEERING COLLEGE


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

4.10 SupportforOOPinAda95–CO4
 GeneralCharacteristics
– OOPwasoneofthemostimportantextensionstoAda83
– Encapsulationcontainerisapackagethatdefinesataggedtype
– Ataggedtypeisoneinwhicheveryobjectincludesatagtoindicateduringexecutionitstype(thetagsare
internal)
– Taggedtypescanbeeitherprivatetypesorrecords
– Noconstructorsordestructorsareimplicitlycalled
 Inheritance
– Subclassescanbederivedfromtaggedtypes
– Newentitiesareaddedtotheinheritedentitiesbyplacingtheminarecorddefinition
– Allsubclassesaresubtypes
– Nosupportformultipleinheritance
 AcomparableeffectcanbeachievedusinggenericclassesExampleofaTag
gedType
PackagePerson_Pkgis
typePersonistaggedprivate;proced
ureDisplay(P:inoutPerson);
private
typePersonistaggedrec
ord
Name:String(1..30);Ad
dress:String(1..30);Ag
e:Integer;
endrecord;e
ndPerson_Pkg;
withPerson_Pkg;usePerson_Pkg;pac
kageStudent_Pkgis
typeStudentisnewPersonwithre
cord
Grade_Point_Average:Floa
t;Grade_Level:Integer;
endrecord;
procedureDisplay(St:inStudent)
;endStudent_Pkg;

PET ENGINEERING COLLEGE


//Note:DisplayisbeingoverriddenfromPerson_Pkg
 DynamicBinding
– Dynamicbindingisdoneusingpolymorphicvariablescalledclasswidetypes
 ForthetaggedtypePrtdon,theclasswidetypeisPerson‘class
– Otherbindingsarestatic

PET ENGINEERING COLLEGE


– Anymethodmaybedynamicallybound
– PurelyabstractbasetypescanbedefinedinAda95byincludingthereservedwordabstract
 Evaluation
– AdaofferscompletesupportforOOP
– C++offersbetterformofinheritancethanAda
– Adaincludesnoinitializationofobjects(e.g.,constructors)
– DynamicbindinginC-basedOOPlanguagesisrestrictedtopointersand/
orreferencestoobjects;Adahasnosuchrestrictionandisthusmoreorthogonal

ImplementingOOPsConstructs
 Twointerestingandchallengingparts
– Storagestructuresforinstancevariables
– Dynamicbindingofmessagestomethods
InstanceDataStorage
 Classinstancerecords(CIRs)storethestateofanobject
– Static(builtatcompiletime)
 Ifaclasshasaparent,thesubclassinstancevariablesareaddedtotheparentCIR
 BecauseCIRisstatic,accesstoallinstancevariablesisdoneasitisinrecords
– Efficient
DynamicBindingofMethodsCalls
 MethodsinaclassthatarestaticallyboundneednotbeinvolvedintheCIR;methodsthatwillbedynam
icallyboundmusthaveentriesintheCIR
– CallstodynamicallyboundmethodscanbeconnectedtothecorrespondingcodethruapointerintheCI
R
– Thestoragestructureissometimescalledvirtualmethodtables(vtable)
– Methodcallscanberepresentedasoffsetsfromthebeginningofthevtable
SummaryofOOPs
 OOprogramminginvolvesthreefundamentalconcepts:ADTs,inheritance,dynamicbinding
 Majordesignissues:exclusivityofobjects,subclassesandsubtypes,typecheckingandpolymorphism,si
ngleandmultipleinheritance,dynamicbinding,explicitandimplicitde-
allocationofobjects,andnestedclasses
 SmalltalkisapureOOL
 C++hastwodistincttypesystem(hybrid)
 JavaisnotahybridlanguagelikeC++;itsupportsonlyOOprogramming
 C#isbasedonC++andJava
 ImplementingOOPinvolvessomenewdatastructures

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

PET ENGINEERING COLLEGE


levelconcurrency,theyarenotaddressedhere

PET ENGINEERING COLLEGE


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

Subprogram-LevelConcurrency
 Ataskorprocessisaprogramunitthatcanbeinconcurrentexecutionwithotherprogramunits
 Tasksdifferfromordinarysubprogramsinthat:
– Ataskmaybeimplicitlystarted
– Whenaprogramunitstartstheexecutionofatask,itisnotnecessarilysuspended
– Whenatask‘sexecutioniscompleted,controlmaynotreturntothecaller
 Tasksusuallyworktogether
TwoGeneralCategoriesofTasks
 Heavyweighttasksexecuteintheirownaddressspace
 Lightweighttasksallruninthesameaddressspace
 Ataskisdisjointifitdoesnotcommunicatewithoraffecttheexecutionofanyothertaskintheprograminan
yway
TaskSynchronization
 Amechanismthatcontrolstheorderinwhichtasksexecute
 Twokindsofsynchronization
– Cooperationsynchronization
– Competitionsynchronization
 Taskcommunicationisnecessaryforsynchronization,providedby:
– Sharednonlocalvariables
– Parameters
– Messagepassing
Kindsofsynchronization
 Cooperation:TaskAmustwaitfortaskBtocompletesomespecificactivitybeforetaskAcancontinueitse

PET ENGINEERING COLLEGE


xecution,e.g.,theproducer-consumerproblem

PET ENGINEERING COLLEGE


 Competition:Twoormoretasksmustusesomeresourcethatcannotbesimultaneouslyused,e.g.,ash
aredcounter
– Competitionisusuallyprovidedbymutuallyexclusiveaccess(approachesarediscussedlater)

Scheduler Figure6.1NeedforCompetitionSynchronization
 Providingsynchronizationrequiresamechanismfordelayingtaskexecution
 Taskexecutioncontrolismaintainedbyaprogramcalledthescheduler,whichmapstaskexecutiono
ntoavailableprocessors
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
 Asemaphoreisadatastructureconsistingofacounterandaqueueforstoringtaskdescriptors
 Semaphorescanbeusedtoimplementguardsonthecodethataccessesshareddatastructures

PET ENGINEERING COLLEGE


 Semaphoreshaveonlytwooperations,waitandrelease(originallycalledPand
VbyDijkstra)

PET ENGINEERING COLLEGE


 Semaphores can be used to provide both competition and
cooperationsynchronization
CooperationSynchronizationwithSemaphores
 Example:Asharedbuffer
 ThebufferisimplementedasanADTwiththeoperationsDEPOSITandFETCHastheonlywaystoaccess
thebuffer
 Usetwosemaphoresforcooperation:emptyspotsandfullspots
 Thesemaphorecountersareusedtostorethenumbersofemptyspotsandfullspotsinthebuffer
 DEPOSITmustfirstcheckemptyspotstoseeifthereisroominthebuffer
 Ifthereisroom,thecounterofemptyspotsisdecrementedandthevalueisinserted
 Ifthereisnoroom,thecallerisstoredinthequeueofemptyspots
 WhenDEPOSITisfinished,itmustincrementthecounteroffullspots
 FETCHmustfirstcheckfullspotstoseeifthereisavalue
– Ifthereisafullspot,thecounteroffullspotsisdecrementedandthevalueisremoved
– Iftherearenovaluesinthebuffer,thecallermustbeplacedinthequeueoffullspots
– WhenFETCHisfinished,itincrementsthecounterofemptyspots
 TheoperationsofFETCHandDEPOSITonthesemaphoresareaccomplishedthroughtwosemapho
reoperationsnamedwaitandrelease

Semaphores:WaitOperation
wait(aSemaphore)
ifaSemaphore‘scounter>0thendecrem
entaSemaphore‘scounter
else
putthecallerinaSemaphore‘squeueatte
mpttotransfercontroltoareadytask
--ifthetaskreadyqueueisempty,
--deadlockoccurs
end

Semaphores:ReleaseOperation
release(aSemaphore)
ifaSemaphore‘squeueisemptythenincreme
ntaSemaphore‘scounter
els
e putthecallingtaskinthetaskreadyqueuetransferco
ntroltoataskfromaSemaphore‘squeue
end

ProducerConsumerCode
semaphorefullspots,emptyspots;full
stops.count=0;emptyspots.c
ount=BUFLEN;taskproduc
er;
loop
--produceVALUE–-
wait(emptyspots);

PET ENGINEERING COLLEGE


{waitforspace}DEPOSIT(VALUE);
release(fullspots);
{increasefilled}endloop;
endproducer;

PET ENGINEERING COLLEGE


ProducerConsumerCode
taskconsumer;
loop
wait(fullspots);
{waittillnotempty}}FETCH(VALUE);
release(emptyspots);{increaseempty}
--consumeVALUE–-
endloop;
endconsumer;
CompetitionSynchronizationwithSemaphores
 Athirdsemaphore,namedaccess,isusedtocontrolaccess(competitionsynchronization)
– Thecounterofaccesswillonlyhavethevalues0and1
– Suchasemaphoreiscalledabinarysemaphore
 Notethatwaitandreleasemustbeatomic!
ProducerConsumerCode
semaphoreaccess,fullspots,emptyspots;access.co
unt=0;
fullstops.count=0;emptyspo
ts.count=BUFLEN;taskpro
ducer;
loop
--produceVALUE–-
wait(emptyspots);
{waitforspace}wait(access);
{waitforaccess)DEPOSIT(VALUE);
release(access);
{relinquishaccess}release(fullspots);
{increasefilled}
endloop;
endproducer;

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

PET ENGINEERING COLLEGE


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

PET ENGINEERING COLLEGE


– Monitorimplementationguaranteesynchronizedaccessbyallowingonlyoneaccessatatime
– Callstomonitorproceduresareimplicitlyqueuedifthemonitorisbusyatthetimeofthecall
CooperationSynchronization
 Cooperationbetweenprocessesisstillaprogrammingtask
– Programmermustguaranteethatasharedbufferdoesnotexperienceunderfloworoverflow

EvaluationofMonitors Figure6.2CooperationSynchronization
 Abetterwaytoprovidecompetitionsynchronizationthanaresemaphores
 Semaphorescanbeusedtoimplementmonitors
 Monitorscanbeusedtoimplementsemaphores
 Supportforcooperationsynchronizationisverysimilaraswithsemaphores,soithasthesameproble
ms

MessagePassing
 Messagepassingisageneralmodelforconcurrency
– Itcanmodelbothsemaphoresandmonitors
– Itisnotjustforcompetitionsynchronization
 Centralidea:taskcommunicationislikeseeingadoctor--
mostofthetimeshewaitsforyouoryouwaitforher,butwhenyouarebothready,yougettogether,orrendez
vous
MessagePassingRendezvous
 Tosupportconcurrenttaskswithmessagepassing,alanguageneeds:
– Amechanismtoallowatasktoindicatewhenitiswillingtoacceptmessages
– Awaytorememberwhoiswaitingtohaveitsmessageacceptedandsome
“fair”wayofchoosingthenextmessage
 Whenasendertask‘smessageisacceptedbyareceivertask,theactualmessagetransmissioniscalled
arendezvous

AdaSupportforConcurrency
 TheAda83Message-PassingModel
– Adataskshavespecificationandbodyparts,likepackages;thespechastheinterface,whichisthec
ollectionofentrypoints:
taskTask_Exampleis
entryENTRY_1(Item:inInteger);en
dTask_Example;

PET ENGINEERING COLLEGE


TaskBody
 Thebodytaskdescribestheactionthattakesplacewhenarendezvousoccurs
 Ataskthatsendsamessageissuspendedwhilewaitingforthemessagetobeacceptedandduringtherendez
vous
 Entrypointsinthespecaredescribedwithacceptclausesinthebodyaccept
entry_name(formalparameters)do

endentry_name

ExampleofaTaskBody
taskbodyTask_Exampleisbe
gin
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(theexampleaboveisaservertask
)

PET ENGINEERING COLLEGE


 Ataskwithoutacceptclausesiscalledanactortask
– Anactortaskcansendmessagestoothertasks
– Note:Asendermustknowtheentrynameofthereceiver,butnotviceversa(asymmetric)

PET ENGINEERING COLLEGE


Figure6.4GraphicalRepresentationofaRendezvous

Example:ActorTask
taskWater_Monitor;--specificationtaskbodybodyWater_Monitoris--
bodybegin
loop
ifWater_Level>Max_Level
thenSound_Alarm;
endif;
delay1.0;--Nofurtherexecution
--foratleast1second
endloop;en
dWater_Monitor;
MultipleEntryPoints
 Taskscanhavemorethanoneentrypoint
– Thespecificationtaskhasanentryclauseforeach
– Thetaskbodyhasanacceptclauseforeachentryclause,placedinaselectclause,whichisinaloop
ATaskwithMultipleEntries
taskbodyTellerisloo
p
select
acceptDrive_Up(formalparams)do
...
endDrive_Up;
...
or
acceptWalk_Up(formalparams)do
...
endWalk_Up;
...
endselect;en
dloop;
endTeller;

SemanticsofTaskswithMultipleacceptClauses

PET ENGINEERING COLLEGE


 Ifexactlyoneentryqueueisnonempty,chooseamessagefromit
 Ifmorethanoneentryqueueisnonempty,chooseone,nondeterministically,fromwhichtoacceptam
essage
 Ifallareempty,wait
 Theconstructisoftencalledaselectivewait
 Extendedacceptclause-codefollowingtheclause,butbeforethenextclause
– Executedconcurrentlywiththecaller

PET ENGINEERING COLLEGE


CooperationSynchronizationwithMessagePassing
 ProvidedbyGuardedacceptclauses
whennotFull(Buffer)=>acceptDep
osit(New_Value)do
 Anacceptclausewithawithawhenclauseiseitheropenorclosed
– Aclausewhoseguardistrueiscalledopen
– Aclausewhoseguardisfalseiscalledclosed
– Aclausewithoutaguardisalwaysopen

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

ExampleofaTaskwithGuardedacceptClauses
 Note:Thestationmaybeoutofgasandtheremayormaynotbeapositionavailableinthegarage
taskGas_Station_Attendantis
entryService_Island(Car:Car_Type);entryGa
rage(Car:Car_Type);
endGas_Station_Attendant;

ExampleofaTaskwithGuardedacceptClauses
taskbodyGas_Station_Attendantisbegin
loop
select
whenGas_Available=>
acceptService_Island(Car:Car_Type)doFill_With_Gas(Car);
endService_Island;or
whenGarage_Available=>
acceptGarage(Car:Car_Type)doFix(Car
);
endGarage;else

endselect;e Sleep;
ndloop;
endGas_Station_Attendant;
CompetitionSynchronizationwithMessagePassing
 Modelingmutuallyexclusiveaccesstoshareddata
 Example--asharedbuffer
 Encapsulatethebufferanditsoperationsinatask
 Competitionsynchronizationisimplicitinthesemanticsofacceptclauses
– Onlyoneacceptclauseinataskcanbeactiveatanygiventime

PET ENGINEERING COLLEGE


TaskTermination
 Theexecutionofataskiscompletedifcontrolhasreachedtheendofitscodebody
 Ifataskhascreatednodependenttasksandiscompleted,itisterminated
 Ifataskhascreateddependenttasksandiscompleted,itisnotterminateduntilallitsdependenttasksareter
minated
TheterminateClause
 Aterminateclauseinaselectisjustaterminatestatement
 Aterminateclauseisselectedwhennoacceptclauseisopen
 Whenaterminateisselectedinatask,thetaskisterminatedonlywhenitsmasterandallofthedependentsofi
tsmasterareeithercompletedorarewaitingataterminate
 Ablockorsubprogramisnotleftuntilallofitsdependenttasksareterminated
MessagePassingPriorities
 ThepriorityofanytaskcanbesetwiththepragmaprioritypragmaPriority(expression);
 Thepriorityofataskappliestoitonlywhenitisinthetaskreadyqueue

BinarySemaphores
 ForsituationswherethedatatowhichaccessistobecontrolledisNOTencapsulatedinatask
taskBinary_Semaphoreise
ntryWait;
entryrelease;en
dBinary_Semaphore;
taskbodyBinary_Semaphoreisbe
gin
loop
acceptWait;acce
ptRelease;endlo
op;
endBinary_Semaphore;

ConcurrencyinAda95
 Ada95includesAda83featuresforconcurrency,plustwonewfeatures
– Protectedobjects:Amoreefficientwayofimplementingshareddatatoallowaccesstoashareddatastructu
retobedonewithoutrendezvous
– Asynchronouscommunication

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

AsynchronousCommunication
 Providedthroughasynchronousselectstructures
 Anasynchronousselecthastwotriggeringalternatives,anentryclauseoradelay

PET ENGINEERING COLLEGE


– Theentryclauseistriggeredwhensentamessage
– Thedelayclauseistriggeredwhenitstimelimitisreached

PET ENGINEERING COLLEGE


EvaluationoftheAda
 Messagepassingmodelofconcurrencyispowerfulandgeneral
 Protectedobjectsareabetterwaytoprovidesynchronizedshareddata
 Intheabsenceofdistributedprocessors,thechoicebetweenmonitorsandtaskswithmessagepassingisso
mewhatamatteroftaste
 Fordistributedsystems,messagepassingisabettermodelforconcurrency

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

ThreadmyTh=newMyThread();myTh
.start();

ControllingThreadExecution
 TheThreadclasshasseveralmethodstocontroltheexecutionofthreads
– Theyieldisarequestfromtherunningthreadtovoluntarilysurrendertheprocessor
– Thesleepmethodcanbeusedbythecallerofthemethodtoblockthethread
– Thejoinmethodisusedtoforceamethodtodelayitsexecutionuntiltherunmethodofanotherthreadha
scompleteditsexecution

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

CompetitionSynchronizationwithJavaThreads
 Amethodthatincludesthesynchronizedmodifierdisallowsanyothermethodfromrunningontheobject
whileitisinexecution

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

 Theabovetwomethodsaresynchronizedwhichpreventsthemfrominterferingwitheachother
 Ifonlyapartofamethodmustberunwithoutinterference,itcanbesynchronizedthroughsynchronizedstat
ement
synchronized(expression)
statement
CooperationSynchronizationwithJavaThreads
 CooperationsynchronizationinJavaisachievedviawait,notify,andnotifyAllmethods

PET ENGINEERING COLLEGE


– AllmethodsaredefinedinObject,whichistherootclassinJava,soallobjectsinheritthem
 Thewaitmethodmustbecalledinaloop

PET ENGINEERING COLLEGE


 Thenotifymethodiscalledtotellonewaitingthreadthattheeventitwaswaitinghashappened
 ThenotifyAllmethodawakensallofthethreadsontheobject‘swaitlist

Java’sThreadEvaluation
 Java‘ssupportforconcurrencyisrelativelysimplebuteffective
 NotaspowerfulasAda‘stasks

C#Threads
 LooselybasedonJavabuttherearesignificantdifferences
 Basicthreadoperations
– Anymethodcanruninitsownthread
– AthreadiscreatedbycreatingaThreadobject
– Creatingathreaddoesnotstartitsconcurrentexecution;itmustberequestedthroughtheStartmet
hod
– AthreadcanbemadetowaitforanotherthreadtofinishwithJoin
– AthreadcanbesuspendedwithSleep
– AthreadcanbeterminatedwithAbort

SynchronizingThreads
 ThreewaystosynchronizeC#threads
– TheInterlockedclass
 Usedwhentheonlyoperationsthatneedtobesynchronizedareincrementingordecrementingofanintege
r
– 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:Provideamechanismthattheprogrammercanusetoinformcompilerofwaysitcanmapthepro
gramontomultiprocessorarchitecture
 Minimizecommunicationamongprocessorsandthememoriesoftheotherprocessors
High-PerformanceFortran
 Acollectionofextensionsthatallowtheprogrammertoprovideinformationtothecompilertohelpitopti
mizecodeformultiprocessorcomputers
 Specifythenumberofprocessors,thedistributionofdataoverthememoriesofthoseprocessors,andtheali
gnmentofdata
PrimaryHPFSpecifications
 Numberofprocessors
!HPF$PROCESSORSprocs(n)

PET ENGINEERING COLLEGE


 Distributionofdata
!HPF$DISTRIBUTE(kind)ONTOprocs::identifier_list
– kindcanbeBLOCK(distributedatatoprocessorsinblocks)orCY
CLIC(distributedatatoprocessorsoneelementatatime)

PET ENGINEERING COLLEGE


 Relatethedistributionofonearraywiththatofanother
ALIGNarray1_elementWITHarray2_element
Statement-
LevelConcurrencyExampleREALli
st_1(1000),list_2(1000)INTEGERlist
_3(500),list_4(501)
!HPF$PROCESSORSproc(10)
!HPF$DISTRIBUTE(BLOCK)ONTOprocs::
list_1,list_2
!
HPF$ALIGNlist_1(index)WITHlis
t_4(index+1)

list_1(index)=list_2(index)list
_3(index)=list_4(index+1)
 FORALLstatementisusedtospecifyalistofstatementsthatmaybeexecutedconcurrently
FORALL(index=1:1000)
list_1(index)=list_2(index)
 Specifiesthatall1,000RHSsoftheassignmentscanbeevaluatedbeforeanyassignmenttakesplace

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

PET ENGINEERING COLLEGE


ExceptionHandling&LogicProgrammingLanguage

IntroductiontoExceptionHandling
 Inalanguagewithoutexceptionhandling
– Whenanexceptionoccurs,controlgoestotheoperatingsystem,whereamessageisdisplayedandthep
rogramisterminated
 Inalanguagewithexceptionhandling
– Programsareallowedtotrapsomeexceptions,therebyprovidingthepossibilityoffixingtheproblem
andcontinuing
4.11 BasicConcepts–CO3
 Manylanguagesallowprogramstotrapinput/outputerrors(includingEOF)
 Anexceptionisanyunusualevent,eithererroneousornot,detectablebyeitherhardwareorsoftware,thatm
ayrequirespecialprocessing
 Thespecialprocessingthatmayberequiredafterdetectionofanexceptioniscalledexceptionhandling
 Theexceptionhandlingcodeunitiscalledanexceptionhandler

ExceptionHandlingAlternatives
 Anexceptionisraisedwhenitsassociatedeventoccurs
 Alanguagethatdoesnothaveexceptionhandlingcapabilitiescanstilldefine,detect,raise,andhandle
exceptions(userdefined,softwaredetected)
 Alternatives:
– Sendanauxiliaryparameterorusethereturnvaluetoindicatethereturnstatusofasubprogram
– 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?

PET ENGINEERING COLLEGE


Figure7.1ExceptionHandlingControlFlow

4.12 ExceptionHandlinginAda–CO3
 TheframeofanexceptionhandlerinAdaiseitherasubprogrambody,apackagebody,atask,orablock
 Becauseexceptionhandlersareusuallylocaltothecodeinwhichtheexceptioncanberaised,theydonotha
veparameters
AdaExceptionHandlers
 Handlerform:
whenexception_choice{|exception_choice}=>statement_sequence
...
[whenothers=>statement_sequenc
e]
exception_choiceform:exceptio
n_name|others
 Handlersareplacedattheendoftheblockorunitinwhichtheyoccur
BindingExceptionstoHandlers
 Iftheblockorunitinwhichanexceptionisraiseddoesnothaveahandlerforthatexception,theexceptionis
propagatedelsewheretobehandled
– Procedures-propagateittothecaller
– Blocks-propagateittothescopeinwhichitappears
– Packagebody-
propagateittothedeclarationpartoftheunitthatdeclaredthepackage(ifitisalibraryunit,theprogrami
sterminated)
– Task-nopropagation;ifithasahandler,executeit;ineithercase,markit"completed"
Continuation
 Theblockorunitthatraisesanexceptionbutdoesnothandleitisalwaysterminated(alsoanyblockorunitto
whichitispropagatedthatdoesnothandleit)
OtherDesignChoices
 User-definedExceptionsform:
exception_name_list:exception;
 RaisingExceptionsform:
raise[exception_name]
– (theexceptionnameisnotrequiredifitisinahandler--inthiscase,itpropagatesthesameexception)
 Exceptionconditionscanbedisabledwith:
pragmaSUPPRESS(exception_list)
PredefinedExceptions

PET ENGINEERING COLLEGE


 CONSTRAINT_ERROR-indexconstraints,rangeconstraints,etc.
 NUMERIC_ERROR-
numericoperationcannotreturnacorrectvalue(overflow,divisionbyzero,etc.)

PET ENGINEERING COLLEGE


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

4.13 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,inwhichcaseithandlesallexceptionsnotyethandled

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

UnhandledExceptions
 Anunhandledexceptionispropagatedtothecallerofthefunctioninwhichitisraised
 Thispropagationcontinuestothemainfunction

Continuation
 Afterahandlercompletesitsexecution,controlflowstothefirststatementafterthelasthandlerintheseque

PET ENGINEERING COLLEGE


nceofhandlersofwhichitisanelement
 Otherdesignchoices

PET ENGINEERING COLLEGE


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

4.13 ExceptionHandlinginJava–CO3
 BasedonthatofC++,butmoreinlinewithOOPphilosophy
 AllexceptionsareobjectsofclassesthataredescendantsoftheThrowableclass
ClassesofExceptions
 TheJavalibraryincludestwosubclassesofThrowable:
– Error
o ThrownbytheJavainterpreterforeventssuchasheapoverflow
o Neverhandledbyuserprograms
– Exception
o User-definedexceptionsareusuallysubclassesofthis
o Hastwopredefinedsubclasses,IOExceptionandRuntimeException
e.g.,ArrayIndexOutOfBoundsExceptionandNullPointerException
JavaExceptionHandlers
 LikethoseofC+
+,excepteverycatchrequiresanamedparameterandallparametersmustbedescendantsofThrowable
 SyntaxoftryclauseisexactlythatofC++
 Exceptionsarethrownwiththrow,asinC+
+,butoftenthethrowincludesthenewoperatortocreatetheobject,asin:thrownewMyException();
BindingExceptionstoHandlers
 BindinganexceptiontoahandlerissimplerinJavathanitisinC++
– Anexceptionisboundtothefirsthandlerwithaparameteristhesameclassasthethrownobjectorananc
estorofit
 Anexceptioncanbehandledandrethrownbyincludingathrowinthehandler(ahandlercouldalsothrowad
ifferentexception)
Continuation
 Ifnohandlerisfoundinthemethod,theexceptionispropagatedtothemethod‘scaller
 Ifnohandlerisfound(allthewaytomain),theprogramisterminated
 Toensurethatallexceptionsarecaught,ahandlercanbeincludedinanytryconstructthatcatchesallex
ceptions
– SimplyuseanExceptionclassparameter
– Ofcourse,itmustbethelastinthetryconstruct
CheckedandUncheckedExceptions
 TheJavathrowsclauseisquitedifferentfromthethrowclauseofC++
 ExceptionsofclassErrorandRunTimeExceptionandalloftheirdescendantsarecalleduncheckedex
ceptions;allotherexceptionsarecalledcheckedexceptions

PET ENGINEERING COLLEGE


 Checkedexceptionsthatmaybethrownbyamethodmustbeeither:
– Listedinthethrowsclause,or
– Handledinthemethod

PET ENGINEERING COLLEGE


OtherDesignChoices
 Amethodcannotdeclaremoreexceptionsinitsthrowsclausethanthemethoditoverrides
 Amethodthatcallsamethodthatlistsaparticularcheckedexceptioninitsthrowsclausehasthreealternativ
esfordealingwiththatexception:
– Catchandhandletheexception
– Catchtheexceptionandthrowanexceptionthatislistedinitsownthrowsclause
– Declareitinitsthrowsclauseanddonothandleit
ThefinallyClause
 Canappearattheendofatryconstruct
 Form:
finally{..}
 Purpose:Tospecifycodethatistobeexecuted,regardlessofwhathappensinthetryconstruct
Example
 Atryconstructwithafinallyclausecanbeusedoutsideexceptionhandling
try{
for(index=0;index<100;index++){

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

}//**endoftryconstruct
Assertions
 Statementsintheprogramdeclaringabooleanexpressionregardingthecurrentstateofthecomputati
on
 Whenevaluatedtotruenothinghappens
 WhenevaluatedtofalseanAssertionErrorexceptionisthrown
 Canbedisabledduringruntimewithoutprogrammodificationorrecompilation
 Twoforms
– assertcondition;
– assertcondition:expression;
Evaluation
 ThetypesofexceptionsmakesmoresensethaninthecaseofC++
 ThethrowsclauseisbetterthanthatofC++(ThethrowclauseinC++sayslittletotheprogrammer)
 Thefinallyclauseisoftenuseful
 TheJavainterpreterthrowsavarietyofexceptionsthatcanbehandledbyuserprograms
SummaryofExceptionHandling
 Adaprovidesextensiveexception-handlingfacilitieswithacomprehensivesetofbuilt-inexceptions.
 C+
+includesnopredefinedexceptions.Exceptionsareboundtohandlersbyconnectingthetypeofexpressio
ninthethrowstatementtothatoftheformalparameterofthecatchfunction
 JavaexceptionsaresimilartoC+
+exceptionsexceptthataJavaexceptionmustbeadescendantoftheThrowableclass.AdditionallyJa
vaincludesafinallyclause

PET ENGINEERING COLLEGE


4.14 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,writtenlikeamathematicalfunction
– Mathematicalfunctionisamapping
– Canbewrittenasatable

PartsofaCompoundTerm
 Compoundtermcomposedoftwoparts
– Functor:functionsymbolthatnamestherelationship
– Orderedlistofparameters(tuple)
 Examples:
student(jon)like(set
h,OSX)like(nick,wi
ndows)like(jim,linu
x)

FormsofaProposition
 Propositionscanbestatedintwoforms:
– Fact:propositionisassumedtobetrue
– Query:truthofpropositionistobedetermined

PET ENGINEERING COLLEGE


 Compoundproposition:
– Havetwoormoreatomicpropositions
– Propositionsareconnectedbyoperators

PET ENGINEERING COLLEGE


LogicalOperators
Name Symbol Example Meaning
Negation  a anotb
Conjunction  ab aandb
Disjunction  ab aorb
Equivalence  ab aisequivalenttob
 abab aimpliesb
Implication
 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
 Auseofpropositionsistodiscovernewtheoremsthatcanbeinferredfromknownaxiomsandtheorems
 Resolution:aninferenceprinciplethatallowsinferredpropositionstobecomputedfromgivenpropositio
ns
Resolution
 Unification:findingvaluesforvariablesinpropositionsthatallowsmatchingprocesstosucceed
 Instantiation:assigningtemporaryvaluestovariablestoallowunificationtosucceed
 Afterinstantiatingavariablewithavalue,ifmatchingfails,mayneedto
backtrackandinstantiatewithadifferentvalue

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

AnOverviewofLogicProgramming
 Declarativesemantics
– Thereisasimplewaytodeterminethemeaningofeachstatement
– Simplerthanthesemanticsofimperativelanguages

PET ENGINEERING COLLEGE


 Programmingisnonprocedural
– Programsdonotstatenowaresultistobecomputed,butrathertheformoftheresult

PET ENGINEERING COLLEGE


TheOriginsofProlog
 UniversityofAix-Marseille
– Naturallanguageprocessing
 UniversityofEdinburgh
– Automatedtheoremproving

4.15 TheBasicElementsofProLogCO4
 EdinburghSyntax
 Term:aconstant,variable,orstructure
 Constant:anatomoraninteger
 Atom:symbolicvalueofProlog
 Atomconsistsofeither:
– astringofletters,digits,andunderscoresbeginningwithalowercaseletter
– astringofprintableASCIIcharactersdelimitedbyapostrophes
Terms:VariablesandStructures
 Variable:anystringofletters,digits,andunderscoresbeginningwithanuppercaseletter
 Instantiation:bindingofavariabletoavalue
– Lastsonlyaslongasittakestosatisfyonecompletegoal
 Structure:representsatomicproposition
functor(parameterlist)
FactStatements
 Usedforthehypotheses
 HeadlessHornclauses
female(shelley).
male(bill).father
(bill,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,theoremisinformofpropositionthatwewantsystemtoproveordisprove–
goalstatement

PET ENGINEERING COLLEGE


 SameformatasheadlessHorn
man(fred)
 Conjunctivepropositionsandpropositionswithvariablesalsolegalgoals
father(X,mike)
InferencingProcessofProlog
 Queriesarecalledgoals

PET ENGINEERING COLLEGE


 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,reconsiderprevioussubgoaltofi
ndanalternativesolution:backtracking
 Beginsearchwhereprevioussearchleftoff
 Cantakelotsoftimeandspacebecausemayfindallpossibleproofstoeverysubgoal
SimpleArithmetic
 Prologsupportsintegervariablesandintegerarithmetic
 isoperator:takesanarithmeticexpressionasrightoperandandvariableasleftoperand
AisB/17+C
 Notthesameasanassignmentstatement!
Example
speed(ford,100).speed(c
hevy,105).speed(dodge,
95).speed(volvo,80).tim
e(ford,20).time(chevy,2
1).time(dodge,24).time(
volvo,24).
distance(X,Y):- speed(X,Speed),
time(X,Time),
YisSpeed*Time.
Trace
• Built-instructurethatdisplaysinstantiationsateachstep
• Tracingmodelofexecution-fourevents:
– Call(beginningofattempttosatisfygoal)

PET ENGINEERING COLLEGE


– Exit(whenagoalhasbeensatisfied)

PET ENGINEERING COLLEGE


– Redo(whenbacktrackoccurs)
– Fail(whengoalfails)
Example

likes(jake,chocolate).likes(jake,ap
ricots).likes(darcie,licorice).likes(
darcie,apricots).

trace.likes(ja
ke,X),likes(da
rcie,X).

ListStructures
 Otherbasicdatastructure(besidesatomicpropositionswehavealreadyseen):list
 Listisasequenceofanynumberofelements
 Elementscanbeatoms,atomicpropositions,orotherterms(includingotherlists)
[apple,prune,grape,kumquat][]
(emptylist)
[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),appen
d(Result,[Head],List).
DeficienciesofProlog
 Resolutionordercontrol
 Theclosed-worldassumption
 Thenegationproblem
 Intrinsiclimitations

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

PET ENGINEERING COLLEGE


 Althoughthereareanumberofdrawbackswiththecurrentstateoflogicprogrammingithasbeenusedinan
umberofareas

PET ENGINEERING COLLEGE


UNIT-5
FunctionalProgrammingLanguages&ScriptingLanguage

5.1 FunctionalProgrammingLanguageIntroduction–CO5
 ThedesignoftheimperativelanguagesisbaseddirectlyonthevonNeumannarchitecture
– Efficiencyistheprimaryconcern,ratherthanthesuitabilityofthelanguageforsoftwaredevelopment
 Thedesignofthefunctionallanguagesisbasedonmathematicalfunctions
– Asolidtheoreticalbasisthatisalsoclosertotheuser,butrelativelyunconcernedwiththearchitectureo
fthemachinesonwhichprogramswillrun

MathematicalFunctions
 Amathematicalfunctionisamappingofmembersofoneset,calledthedomainset,toanotherset,calle
dtherangeset
 Alambdaexpressionspecifiestheparameter(s)andthemappingofafunctioninthefollowingform
(x)x*x*x
forthefunctioncube(x)=x*x*x
LambdaExpressions
 Lambdaexpressionsdescribenamelessfunctions
 Lambdaexpressionsareappliedtoparameter(s)byplacingtheparameter(s)aftertheexpression
e.g.,((x)x*x*x)
(2)whichevaluatesto8
FunctionalForms
 Ahigher-
orderfunction,orfunctionalform,isonethateithertakesfunctionsasparametersoryieldsafunctionasitsr
esult,orboth
FunctionComposition
 Afunctionalformthattakestwofunctionsasparametersandyieldsafunctionwhosevalueisthefirsta
ctualparameterfunctionappliedtotheapplicationofthesecond
Form:hf°g
whichmeansh(x)f(g(x))
Forf(x)x+2andg(x)3*x,h
f°gyields(3*x)+2
Apply-to-all
 Afunctionalformthattakesasinglefunctionasaparameterandyieldsalistofvaluesobtainedbyapplyingt
hegivenfunctiontoeachelementofalistofparameters
Form:
Forh(x)x*x
(h,(2,3,4))yields(4,9,16)

5.2 FundamentalsofFunctionalProgrammingLanguages-CO5
 TheobjectiveofthedesignofaFPListomimicmathematicalfunctionstothegreatestextentpossible
 ThebasicprocessofcomputationisfundamentallydifferentinaFPLthaninanimperativelanguage

PET ENGINEERING COLLEGE


– Inanimperativelanguage,operationsaredoneandtheresultsarestoredinvariablesforlateruse
– Managementofvariablesisaconstantconcernandsourceofcomplexityforimperativeprogramming
 InanFPL,variablesarenotnecessary,asisthecaseinmathematics
ReferentialTransparency
 InanFPL,theevaluationofafunctionalwaysproducesthesameresultgiventhesameparameters

TheFirstFunctionalProgrammingLanguage:LISP–CO5

LISPDataTypesandStructures
 Dataobjecttypes:originallyonlyatomsandlists
 Listform:parenthesizedcollectionsofsublistsand/oratoms
e.g.,(AB(CD)E)
 Originally,LISPwasatypelesslanguage
 LISPlistsarestoredinternallyassingle-linkedlists
LISPInterpretation
 Lambdanotationisusedtospecifyfunctionsandfunctiondefinitions.Functionapplicat
ionsanddatahavethesameform.
e.g.,Ifthelist(ABC)isinterpretedasdataitisasimplelistofthreeatoms,A,BandC
Ifitisinterpretedasafunctionapplication,itmeansthatthefunctionnamedAisappliedtothetwopar
ameters,BandC
 ThefirstLISPinterpreterappearedonlyasademonstrationoftheuniversalityofthecomputationalcapabi
litiesofthenotation

5.3ML–CO5
 Astatic-scopedfunctionallanguagewithsyntaxthatisclosertoPascalthantoLISP
 Usestypedeclarations,butalsodoestypeinferencingtodeterminethetypesofundeclaredvariables
 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,soifwewantedacubefunctionforrealparameters,itwo
uldneedtohaveadifferentname
– TherearenotypecoercionsinML
 MLselection
ifexpressionthenthen_expression
elseelse_expression

PET ENGINEERING COLLEGE


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]CARistheunaryoper
atorhd
CDRistheunaryoperatortlfunlengt
h([])=0
|
length(h::t)=1+length(t);funappend(
[],lis2)=lis2
|append(h::t,lis2)=h::append(t,lis2);
 Thevalstatementbindsanametoavalue(similartoDEFINEinScheme)valdistance=time*
speed;
– AsisthecasewithDEFINE,valisnothinglikeanassignmentstatementinanimperativelanguage

5.4 Haskell–CO5
 SimilartoML(syntax,staticscoped,stronglytyped,typeinferencing,patternmatching)
 DifferentfromML(andmostotherfunctionallanguages)inthatitispurelyfunctional(e.g.,novariabl
es,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=1sq
uarex=x*x
- Worksforanynumerictypeofx
Lists
 Listnotation:Putelementsinbrackets
e.g.,directions=["north","south","east","west"]
 Length:#

PET ENGINEERING COLLEGE


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]

PET ENGINEERING COLLEGE


 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:member[]b=
False
member(a:x)b=(a==b)||memberxb
 However,thiswouldonlyworkiftheparametertosquareswasaperfectsquare;ifnot,itwillkeepgeneratin
gthemforever.Thefollowingversionwillalwayswork:
member2(m:x)n
|m<n=member2xn
|m==n=True
|otherwise=False

5.5 ApplicationsofFunctionalLanguages–CO5
 APLisusedforthrow-awayprograms
 LISPisusedforartificialintelligence
– Knowledgerepresentation

PET ENGINEERING COLLEGE


– Machinelearning
– Naturallanguageprocessing
– Modelingofspeechandvision
 Schemeisusedtoteachintroductoryprogrammingatsomeuniversities

PET ENGINEERING COLLEGE


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

SummaryofFunctionalProgrammingLanguages
 Functionalprogramminglanguagesusefunctionapplication,conditionalexpressions,recursion,a
ndfunctionalformstocontrolprogramexecutioninsteadofimperativefeaturessuchasvariablesand
assignments
 LISPbeganasapurelyfunctionallanguageandlaterincludedimperativefeatures
 SchemeisarelativelysimpledialectofLISPthatusesstaticscopingexclusively
 COMMONLISPisalargeLISP-basedlanguage
 MLisastatic-
scopedandstronglytypedfunctionallanguagewhichincludestypeinference,exceptionhandling,a
ndavarietyofdatastructuresandabstractdatatypes
 Haskellisalazyfunctionallanguagesupportinginfinitelistsandsetcomprehension.
 Purelyfunctionallanguageshaveadvantagesoverimperativealternatives,buttheirlowerefficiency
onexistingmachinearchitectureshaspreventedthemfromenjoyingwidespreaduse

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

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

CaseStudy:PYTHON
 PYTHONwasdesignedintheearly1990sbyGuidovanRossum.
 IthasbeenusedtohelpimplementthesuccessfulWebsearchengineGOOGLE,andinavarietyofothe
rapplicationareasrangingfromsciencefiction(visualeffectsfortheStarWarsseries)torealscience(
computer-aideddesigninNASA).

PET ENGINEERING COLLEGE


ValuesandTypes
 PYTHONhasalimitedrepertoireofprimitivetypes:integer,real,andcomplexnumbers.
 Ithasnospecificcharactertype;single-
characterstringsareusedinstead.Itsbooleanvalues(namedFalseandTrue)arejustsmallintegers.
 PYTHONhasarichrepertoireofcompositetypes:tuples,strings,lists,dictionariesandobjects.APYTH
ONlistisaheterogeneoussequenceofvalues.
 Adictionary(sometimescalledanassociativearray)isaheterogeneousmappingfromkeystovalues,whe
rethekeysaredistinctimmutablevalues.
 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’’updatesthefirst
componentofyears,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”inphonesreturnsTrue,an
d‘‘phones.keys()’’returnsalistcontaining‘‘Ali’’,‘‘Carol’’,and‘‘David’’ (innoparticularorder).

Variables,StorageandControl
 PYTHONsupportsglobalandlocalvariables.
 Variablesarenotexplicitlydeclared,simplyinitializedbyassignment.Afterinitialization,avariable
maylaterbeassignedanyvalueofanytype.
 PYTHON’srepertoireofcommandsincludeassignments,procedurecalls,conditional(if-
butnotcase-)commands,iterative(while-andfor-)commandsandexception-handlingcommands.
 However,PYTHONdiffersfromCinnotallowinganassignmenttobeusedasanexpression.
 PYTHONadditionallysupportssimultaneousassignment.
 Forexample:
y,m,d=date
assignsthethreecomponentsofthetupledatetothreeseparatevariables.Also:
m,n=n,m
conciselyswapsthevaluesoftwovariablesmandn.
(Actually,itfirstconstructsapair,thenassignsthetwocomponentsofthepairtothetwoleft-sidevariables)
 PYTHONif-andwhile-commandsareconventional.
 PYTHONfor-commandssupportdefiniteiteration.
 Wecaneasilyachievetheconventionaliterationoverasequenceofnumbersbyusingthelibraryprocedure
range(m,n),whichreturnsalistofintegersfrommthroughn−1.

PET ENGINEERING COLLEGE


 PYTHONsupportsbreak,continue,andreturnsequencers.Italsosupportsexceptions,whichareobj
ectsofasubclassofException,andwhichcancarryvalues.

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

PYTHONExceptions
 Thefollowingcodepromptstheusertoenteranumericliteral,andstoresthecorrespondingrealnumberin
num:
whileTrue:
try:
response=raw_input("Enteranumericliteral:")nu
m=float(response)
break
exceptValueError:
print"Yourresponsewasill-formed."
Thiswhile-commandkeepspromptinguntiltheuserentersawell-
formednumericliteral.Thelibraryprocedureraw_input(...)displaysthegivenpromptandreturnsth
euser’sresponseasastring.Thetypeconversion‘‘float(response)’’
attemptstoconverttheresponsetoarealnumber.Ifthistypeconversionispossible,thefollowingbrea
ksequencerterminatestheloop.Ifnot,thetypeconversionthrowsaValueErrorexception,controlistr
ansferredtotheValueErrorexceptionhandler,whichdisplaysawarningmessage,andfinallytheloo
pisiteratedagain.

BindingsandScope
 APYTHONprogramconsistsofanumberofmodules,whichmaybegroupedintopackages.
 Withinamodulewemayinitializevariables,defineprocedures,anddeclareclasses.Withinaprocedurew
emayinitializelocalvariablesanddefinelocalprocedures.Withinaclasswemayinitializevariablecomp
onentsanddefineprocedures(methods).
 DuringaPYTHONsession,wemayinteractivelyissuedeclarations,commands,andexpressionsfro
mthekeyboard.
 Theseareallacteduponimmediately.Wheneverweissueanexpression,itsvalueisdisplayedonthescreen
.Wemayalsoimportanamedmodule(orselectedcomponentsofit)atanytime.
 PYTHONwasoriginallyadynamically-scopedlanguage,butitisnowstaticallyscoped.

PET ENGINEERING COLLEGE


ProceduralAbstraction
 PYTHONsupportsfunctionproceduresandproperprocedures.
 Theonlydifferenceisthatafunctionprocedurereturnsavalue,whileaproperprocedurereturnsnothing.
 SincePYTHONisdynamicallytyped,aproceduredefinitionstatesthenamebutnotthetypeofeachforma
lparameter.Thecorrespondingargumentmaybeofdifferenttypesondifferentcallstotheprocedure.

PYTHONProcedures
 Thefollowingfunctionprocedurereturnsthegreatestcommondivisorofitstwoarguments:
defgcd(m,n):
p,q=m,n
whilep%q!
=0:p,q=q,p%q
returnq
Herepandqarelocalvariables.
 ThefollowingproperproceduretakesadaterepresentedbyatripleandprintsthatdateinISOformat(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.Itreturnstheminimumand
maximumcomponentofagivensequence:
defminimax(vals):
min=max=vals[0]
forvalinvals:
ifval<min:
min=val
elifval>max:max
=val
returnmin,max
 Inacalltothisprocedure,theargumentmaybeeitheratupleoralist.
 Ineffectithastworesults,whichwecaneasilyseparateusingsimultaneousassignment:
readings=[...]
low,high=minimax(readings)
 SomeolderlanguagessuchasChavelibraryprocedureswithvariablenumbersofarguments.
 PYTHONisalmostuniqueinallowingsuchprocedurestobedefinedbyprogrammers.
 Thisisachievedbythesimpleexpedientofallowingasingleformalparametertorefertoawholetuple(ordi
ctionary)ofarguments.

PET ENGINEERING COLLEGE


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

DataAbstraction
 PYTHONhasthreedifferentconstructsrelevanttodataabstraction:packages,modules,andclasses.
 Modulesandclassessupportencapsulation,usinganamingconventiontodistinguishbetweenpubli
candprivatecomponents.
 Apackageissimplyagroupofmodules.Amoduleisagroupofcomponentsthatmaybevariables,proc
edures,andclasses.
 Thesecomponentsmaybeimportedforusebyanyothermodule.Allcomponentsofamodulearepublic,ex
ceptthosewhoseidentifiersstartwith‘‘_’’ whichareprivate.
 Aclassisagroupofcomponentsthatmaybeclassvariables,classmethods,andinstancemethods.Apr
oceduredefinedinaclassdeclarationactsasaninstancemethodifitsfirstformalparameterisnamedse
lfandreferstoanobjectoftheclassbeingdeclared.Otherwisetheprocedureactsasaclassmethod.
 Toachievetheeffectofaconstructor,weusuallyequipeachclasswithaninitializationmethodnamed‘‘ini
t’’;thismethodisautomaticallycalledwhenanobjectoftheclassisconstructed.Instancevariablesarena
medusingtheusual‘‘.’’Notation(asinself.attr),andtheymaybeinitializedbytheinitializationmethodor
byanyothermethod.Allcomponentsofaclassarepublic,exceptthosewhoseidentifiersstartwith‘‘’’,whi
chareprivate.

PYTHONClass
 Considerthefollowingclass:
classPerson:
definit(self,sname,fname,gender,birth):self.s
urname=sname
self.forename=fname
self.female=(gender=="F"orgender=="f")self.bi
rth=birth
defget_surname(self):
returnself.surname
defchange_surname(self,sname):se
lf.surname=sname
defprint_details(self):
printself.forename+""+self.surname
 Thisclassisequippedwithaninitializationmethodandthreeotherinstancemethods,eachofwhichhasase
lfparameterandperhapssomeotherparameters.Inthefollowingcode:
dw=Person("Watt","David","M",1946)

PET ENGINEERING COLLEGE


theobjectconstructionontherightfirstcreatesanobjectofclassPerson;itthenpassestheabovearguments,
togetherwithareferencetothenewlycreatedobject,totheinitializationmethod.Thelatterinitializestheo
bject’sinstancevariables,whicharenamedsurname,forename,female,andbirth(andthusareallprivate).
 PYTHONsupportsmultipleinheritance:aclassmaydesignateanynumberofsuperclasses.Ambigu
ousreferencestoclasscomponentsareresolvedbysearchingthesuperclassesintheorderinwhichthe
yarenamedintheclassdeclaration.
 PYTHON’ssupportforobject-
orientedprogrammingisdevelopingbutisnotyetmature.Theuseofthe‘‘’’
namingconventiontoindicateprivacyisclumsyanderror-
prone;classcomponentsarepublicbydefault.Stillmoreseriously,variablecomponentscanbecreated(a
nddeleted)atanytime,byanymethodandevenbyapplicationcode.

SeparateCompilation
 PYTHONmodulesarecompiledseparately.Eachmodulemustexplicitlyimporteveryothermodule
onwhichitdepends.Eachmodule’ssourcecodeisstoredinatextfile.
 Forexample,amodulenamedwidgetisstoredinafilenamedwidget.py.Whenthatmoduleisfirstimp
orted,itiscompiledanditsobjectcodeisstoredinafilenamedwidget.pyc.
 Wheneverthemoduleissubsequentlyimported,itisrecompiledonlyifthesourcecodehasbeenedite
dinthemeantime.Compilationiscompletelyautomatic.
 ThePYTHONcompilerdoesnotrejectcodethatreferstoundeclaredidentifiers.Suchcodesimplyfailsifa
ndwhenitisexecuted.
ModuleLibrary
 PYTHONisequippedwithaveryrichmodulelibrary,whichsupportsstringhandling,markup,mathemat
icsandcryptography,multimedia,GUIs,operatingsystemservices,Internetservices,compilation,ands
oon.
 Unlikeolderscriptinglanguages,PYTHONdoesnothavebuilt-inhigh-
levelstringprocessingorGUIsupport.Instead,thePYTHONmodulelibraryprovidessuchfunction
ality.Forexample,therelibrarymoduleprovidespowerfulstringmatchingfacilitiesusingregularex
pressions.

SummaryofScriptingLanguages
 Thepragmaticissuesthatinfluencethedesignofscriptinglanguages:gluing,rapiddevelopmentand
evolution,modestefficiencyrequirements,andveryhigh-levelfunctionalityinrelevantareas.
 Theconceptscommontomostscriptinglanguages:veryhigh-
levelsupportforstringprocessing,veryhigh-levelsupportforGUIs,anddynamictyping.
 ThedesignofamajorscriptinglanguagePYTHON,resemblesaconventionalprogramminglanguage,ex
ceptthatitisdynamicallytyped,andthatitderivesmuchofitsexpressivenessfromarichmodulelibrary.

PET ENGINEERING COLLEGE

You might also like