PPL Notes Pet
PPL Notes Pet
PE
SUBJECT CODE : CCS358
REGULATION :2021
YEAR/SEM :III/VI
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
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
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)
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)
ComputerArchitecture
Well-knowncomputerarchitecture:VonNeumann
Imperativelanguages,mostdominant,becauseofvonNeumanncomputers
– Dataandprogramsstoredinmemory
– MemoryisseparatefromCPU
– InstructionsanddataarepipedfrommemorytoCPU
– Basisforimperativelanguages
Variablesmodelmemorycells
Assignmentstatementsmodelpiping
Iterationisefficient
Figure1.1ThevonNeumannComputerArchitecture
ProgrammingMethodologies
1950sandearly1960s:Simpleapplications;worryaboutmachineefficiency
Late1960s:Peopleefficiencybecameimportant;readability,bettercontrolstructures
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
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)
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
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:
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
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)
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_typelookup(<var>.string)
Howareattributevaluescomputed?
– Ifallattributeswereinherited,thetreecouldbedecoratedintop-downorder.
– Ifallattributesweresynthesized,thetreecouldbedecoratedinbottom-uporder.
– Inmanycases,bothkindsofattributesareused,anditissomecombinationoftop-
downandbottom-upthatmustbeused.
<expr>.expected_typeinheritedfromparent
<var>[1].actual_typelookup(A)
<var>[2].actual_typelookup(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
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.
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
Summary
BNFandcontext-freegrammarsareequivalentmeta-languages
– Well-suitedfordescribingthesyntaxofprogramminglanguages
Anattributegrammarisadescriptiveformalismthatcandescribeboththesyntaxandtheseman
ticsofalanguage
Threeprimarymethodsofsemanticsdescription
– Operation,axiomatic,denotational
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
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++)
Figure3.1Compile-TimeDescriptor Figure3.2Run-TimeDescriptors
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
dynamicallyboundandthestorageallocationisdynamic(doneatrun-time)
– Advantage:flexibility(thesizeofanarrayneednotbeknownuntilthearrayistobeused)
Fixedheap-dynamic:similartofixedstack-
dynamic:storagebindingisdynamicbutfixedafterallocation(i.e.,bindingisdonewhenrequestedandsto
rageisallocatedfromheap,notstack)
Heap-
dynamic:bindingofsubscriptrangesandstorageallocationisdynamicandcanchangeanynumberof
times
– Advantage:flexibility(arrayscangroworshrinkduringprogramexecution)
SliceExamples Figure3.3SlicesExamplesinFortran95
– Fortran95
Integer,Dimension(10)::VectorInte
ger,Dimension(3,3)::Mat
Integer,Dimension(3,3)::Cube
Vector(3:6)isafourelementarray
ImplementationofArrays
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.
Figure3.7ImplementationofRecordType
UnionsTypes
Aunionisatypewhosevariablesareallowedtostoredifferenttypevaluesatdifferenttimesduringexecuti
on
Designissues
– Shouldtypecheckingberequired?
– Shouldunionsbeembeddedinrecords?
Discriminatedvs.FreeUnions
Fortran,C,andC+
+provideunionconstructsinwhichthereisnolanguagesupportfortypechecking;theunioninthesela
nguagesiscalledfreeunion
Typecheckingofunionsrequirethateachunionincludeatypeindicatorcalledadiscriminant
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
Figure3.10MarkingAlgorithm
Variable-SizeCells
Allthedifficultiesofsingle-sizecellsplusmore
Requiredbymostprogramminglanguages
Ifmark-sweepisused,additionalproblemsoccur
– Theinitialsettingoftheindicatorsofallcellsintheheapisdifficult
PET ENGINEERING COLLEGE
– Themarkingprocessinnontrivial
– Maintainingthelistofavailablespaceisanothersourceofoverhead
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
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
2.5 TypeChecking-CO3
Generalizetheconceptofoperandsandoperatorstoincludesubprogramsandassignments
Typecheckingistheactivityofensuringthattheoperandsofanoperatorareofcompatibletypes
Acompatibletypeisonethatiseitherlegalfortheoperator,orisallowedunderlanguagerulestobeimplicitl
yconverted,bycompiler-generatedcode,toalegaltype.Thisautomaticconversioniscalledascoercion.
Atypeerroristheapplicationofanoperatortoanoperandofaninappropriatetype
Ifalltypebindingsarestatic,nearlyalltypecheckingcanbestatic
Iftypebindingsaredynamic,typecheckingmustbedynamic
Def:Aprogramminglanguageisstronglytypediftypeerrorsarealwaysdetected
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
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
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.
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.
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
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);
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)
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
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?
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)
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
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
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
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
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
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
Figure5.2PossibleExecutionControls Figure5.3PossibleExecutionControls
Summary Figure5.4PossibleExecutionControlswithLoops
Asubprogramdefinitiondescribestheactionsrepresentedbythesubprogram
Subprogramscanbeeitherfunctionsorprocedures
Localvariablesinsubprogramscanbestack-dynamicorstatic
Threemodelsofparameterpassing:inmode,outmode,andinoutmode
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
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
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;
4.5 Object-OrientedProgramming–CO4
Abstractdatatypes
Inheritance
– InheritanceisthecentralthemeinOOPandlanguagesthatsupportit
Polymorphism
Inheritance
4.6 DesignIssuesforOOPLanguages–CO4
TheExclusivityofObjects
AreSubclassesSubtypes?
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
4.9 SupportforOOPinC#-CO4
Generalcharacteristics
– SupportforOOPsimilartoJava
– Includesbothclassesandstructs
– ClassesaresimilartoJava‘sclasses
– structsarelesspowerfulstack-dynamicconstructs(e.g.,noinheritance)
Inheritance
– UsesthesyntaxofC++fordefiningclasses
– Amethodinheritedfromparentclasscanbereplacedinthederivedclassbymarkingitsdefinitionwith
new
– Theparentclassversioncanstillbecalledexplicitlywiththeprefixbase:base.Draw()
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;
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-
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
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
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);
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
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;
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
)
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
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
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
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
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)
Summary
Concurrentexecutioncanbeattheinstruction,statement,orsubprogramlevel
Physicalconcurrency:whenmultipleprocessorsareusedtoexecuteconcurrentunits
Logicalconcurrency:concurrentunitedareexecutedonasingleprocessor
Two primary facilities to support subprogram concurrency:
competitionsynchronizationandcooperationsynchronization
Mechanisms:semaphores,monitors,rendezvous,threads
High-
PerformanceFortranprovidesstatementsforspecifyinghowdataistobedistributedoverthememoryunit
sconnectedtomultipleprocessors
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?
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
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
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
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
Quantifiers
Name Example Meaning
universal X.P ForallX,Pistrue
existential X.P ThereexistsavalueofXsuchthatPistrue
ClausalForm
Toomanywaystostatethesamething
Useastandardformforpropositions
Clausalform:
– B1B2…BnA1A2…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
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
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
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
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
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:#
5.5 ApplicationsofFunctionalLanguages–CO5
APLisusedforthrow-awayprograms
LISPisusedforartificialintelligence
– Knowledgerepresentation
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).
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.
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.
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.
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)
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.