ICE1341 ICE1341 Programming Languages Programming Languages Spring 2005 Spring 2005 Lecture #9 Lecture #9 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)
Dec 18, 2015
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #9Lecture #9
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
Spring 2005 2 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Binding Lifetimes (cont.)Binding Lifetimes (cont.) WWW ConceptsWWW Concepts WWW LanguagesWWW Languages
XML (Extended Markup Language)XML (Extended Markup Language)
Last LectureLast Lecture
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
This LectureThis Lecture
Scope RulesScope Rules Data TypesData Types
Primitive TypesPrimitive Types Character String Data TypesCharacter String Data Types User-defined Data TypesUser-defined Data Types ArraysArrays
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
An XML-based Programming LanguageAn XML-based Programming Language
<program><program><var name=“result” type=“integer”><init>0</init></var><var name=“result” type=“integer”><init>0</init></var><function name=“factorial”><function name=“factorial”> <return Type=“integer”/><return Type=“integer”/> <param no=“1” name=“n” type=“integer”/><param no=“1” name=“n” type=“integer”/> <block><block>
<if><equal><left>n</left><right>1</right></equal></if><if><equal><left>n</left><right>1</right></equal></if> <then><return>n</return></then><then><return>n</return></then> <else><else> <block> <block> <var name=“val” type=“integer”/><var name=“val” type=“integer”/>
<assignment><assignment> <left>val</left><left>val</left> <right><right> <multiplication><multiplication> <left>n</left><left>n</left> <right><call name=“factorial”><right><call name=“factorial”> <param no=“1”><minus><left>n</left><right>1</right></minus></param><param no=“1”><minus><left>n</left><right>1</right></minus></param> </call></right></call></right> </multiplication></multiplication> </right></right></assignment></assignment>
</block></block> </else></else>
</block></block></function></function><assignment><left>result</left><right><call name=“factorial”><param no=“1”>5</param></call></right></assignment><assignment><left>result</left><right><call name=“factorial”><param no=“1”>5</param></call></right></assignment>
</program></program>
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
An ExampleAn Example
class MyClass {class MyClass {
int int myVar1myVar1 = 100, = 100, myVar2myVar2 = 200; = 200;
void myMethod1() {void myMethod1() { System.out.println(System.out.println(myVar1myVar1););
{ { int int myVar1myVar1 = 200; = 200; System.out.println(System.out.println(myVar1myVar1);); System.out.println(this.System.out.println(this.myVar1myVar1);); }} System.out.println(System.out.println(myVar1myVar1););}}
class InnerClass {class InnerClass {
int int myVar1myVar1 = 300; = 300;
void myMethod2() {void myMethod2() { System.out.println(System.out.println(myVar1myVar1););
System.out.println(System.out.println(myVar2myVar2););
System.out.println(MyClass.this.System.out.println(MyClass.this.myVar1myVar1);); }}}}
}}
How many different How many different variables are variables are defined in the defined in the program?program?
In which program In which program units the variables units the variables are visible?are visible?
What are the What are the current values of current values of the variables?the variables?
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
ScopeScope
Scope Scope of a Variable: the range of statements of a Variable: the range of statements over which it is visibleover which it is visible
VisibilityVisibility: a variable is visible in a statement if it : a variable is visible in a statement if it can be referenced in that statementcan be referenced in that statement
Scope RulesScope Rules of a Language: determine how of a Language: determine how references to names are associated with references to names are associated with variablesvariables
Non-local VariablesNon-local Variables: variables that are visible : variables that are visible but not declared in a program unit (block)but not declared in a program unit (block)
Static ScopeStatic Scope: the scope of a variable that can : the scope of a variable that can be determined prior to executionbe determined prior to execution
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
An Example of An Example of Nested Static Nested Static ScopesScopes
class MyClass {class MyClass {
int int myVar1myVar1 = 100, = 100, myVar2myVar2 = 200; = 200;
void myMethod1() {void myMethod1() { System.out.println(System.out.println(myVar1myVar1););
{ { int int myVar1myVar1 = 200; = 200; System.out.println(System.out.println(myVar1myVar1);); System.out.println(this.System.out.println(this.myVar1myVar1);); }} System.out.println(System.out.println(myVar1myVar1););}}
class InnerClass {class InnerClass {
int int myVar1myVar1 = 300; = 300;
void myMethod2() {void myMethod2() { System.out.println(System.out.println(myVar1myVar1););
System.out.println(System.out.println(myVar2myVar2););
System.out.println(MyClass.this.System.out.println(MyClass.this.myVar1myVar1);); }}}}
}}
The The scopescope of myVar1 of myVar1 and myVar2and myVar2
The The scopescope of the local of the local variable, myVar1variable, myVar1
A A blockblock for defining the for defining the local variable, myVar1local variable, myVar1
myVar2 is a myVar2 is a non-local non-local variablevariable in this block in this block
• InnerClass is the InnerClass is the static static parentparent of myVar2 of myVar2
• MyClass is the MyClass is the static static ancestorancestor of myVar2 of myVar2
Accessing the Accessing the hidden hidden variablevariable, myVar1, myVar1
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Program BlocksProgram Blocks
A method of creating static scopes inside program unitsA method of creating static scopes inside program units Introduced in ALGOL 60Introduced in ALGOL 60 Block-structured LanguagesBlock-structured Languages Examples:Examples:
C and C++: C and C++: for (...) {for (...) { int index;int index; ...... }}
Ada: Ada: declare LCL : FLOAT;declare LCL : FLOAT; beginbegin
...... endend
* AW Lecture Notes
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Problems in Static Scoping (1)Problems in Static Scoping (1)
Required procedure Required procedure access: access: MAIN calls A and BMAIN calls A and B A calls C and DA calls C and D B calls A and EB calls A and E
Program StructureProgram Structure
Desirable CallsDesirable Calls
Potential CallsPotential Calls
Spring 2005 10
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Problems in Static Scoping (2)Problems in Static Scoping (2)
Suppose the spec is changed so that Suppose the spec is changed so that D must now access some data in BD must now access some data in B
Solutions:Solutions: Put D in BPut D in B (but then C can no longer call (but then C can no longer call
it and D cannot access A's variables)it and D cannot access A's variables) Move the data from B that D needs to Move the data from B that D needs to
MAINMAIN (but then all procedures can (but then all procedures can access them)access them)
Same problem for procedure accessSame problem for procedure access Overall: static scoping often Overall: static scoping often
encourages many encourages many globalsglobals* AW Lecture Notes
Spring 2005 11
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic ScopeDynamic Scope
The scope of a variable is determined The scope of a variable is determined based on based on calling sequencescalling sequences of program units, not their of program units, not their textual layout (textual layout (temporaltemporal versus versus spatialspatial))
* AW Lecture Notes
AdvantageAdvantage: convenience: convenience DisadvantageDisadvantage: poor readability: poor readability
Reference to x is to SUB1's xReference to x is to SUB1's x
MAIN - declaration of xMAIN - declaration of x
SUB1SUB1 - declaration of x -- declaration of x - ...... call SUB2call SUB2 ......
SUB2SUB2 ...... - reference to x -- reference to x - ... ... ...... call SUB1call SUB1 … …
MAIN calls SUB1SUB1 calls SUB2SUB2 uses x
e.g.,e.g.,
Spring 2005 12
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Other Scoping IssuesOther Scoping Issues
Scope and LifetimeScope and Lifetime In Java, the scope of a variable is In Java, the scope of a variable is spatial (textual)spatial (textual), and , and
the lifetime of the variable is the lifetime of the variable is temporaltemporal In Java, a In Java, a staticstatic variable in a method is statically bound variable in a method is statically bound
to its scope, and is also statically bound to storageto its scope, and is also statically bound to storage Reference EnvironmentsReference Environments
The The referencing environmentreferencing environment of a statement is the of a statement is the collection of all names that are visible in the statementcollection of all names that are visible in the statement
In a In a static-scoped languagestatic-scoped language, it is the local variables plus , it is the local variables plus all of the all of the visible variables in all of the enclosing scopesvisible variables in all of the enclosing scopes
In a In a dynamic-scoped languagedynamic-scoped language, the referencing , the referencing environment is the local variables plus all environment is the local variables plus all visible visible variables in all active subprogramsvariables in all active subprograms
* AW Lecture Notes
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Other Scoping IssuesOther Scoping Issues
Named constantNamed constant: a variable that is bound to a : a variable that is bound to a value value onlyonly when it is bound to storage when it is bound to storage AdvantagesAdvantages: readability and modifiability: readability and modifiability Used to parameterize programsUsed to parameterize programs The binding of values to named constants can be either The binding of values to named constants can be either
static (called static (called manifest constantsmanifest constants) or dynamic) or dynamic Pascal: literals onlyPascal: literals only FORTRAN 90: constant-valued expressionsFORTRAN 90: constant-valued expressions Ada, C++, and Java: expressions of any kindAda, C++, and Java: expressions of any kind
Variable InitializationVariable Initialization: the binding of a variable to : the binding of a variable to a value at the time it is bound to storagea value at the time it is bound to storage If the storage binding of a variable is dynamic, If the storage binding of a variable is dynamic,
initialization is also dynamicinitialization is also dynamic* AW Lecture Notes
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Chapter 6Chapter 6
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Data TypesData Types
A A data typedata type defines a collection of data objects and defines a collection of data objects and a set of predefined operations on those objectsa set of predefined operations on those objects Primitive Data TypesPrimitive Data Types: data types that are not defined in : data types that are not defined in
terms of other types (e.g., int, float, char)terms of other types (e.g., int, float, char) Structured Data TypesStructured Data Types: non-scalar data types that : non-scalar data types that
specify structured organizations of data of other types specify structured organizations of data of other types (e.g., arrays, records)(e.g., arrays, records)
Design issues for all data types:Design issues for all data types: What is the What is the syntaxsyntax of references to variables? of references to variables? What What operationsoperations are defined and how are they specified? are defined and how are they specified?
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Primitive Data Types –Primitive Data Types –Numeric Types (1)Numeric Types (1)
IntegerInteger Its representation usually reflects the hardware (size, Its representation usually reflects the hardware (size,
notation – ones or notation – ones or twos complementtwos complement)) e.g., Java – byte, short, int, long; C – unsigned inte.g., Java – byte, short, int, long; C – unsigned int
Floating-pointFloating-point Model real numbers, but only as Model real numbers, but only as approximationsapproximations IEEE Floating-Point Standard 754 formatIEEE Floating-Point Standard 754 format e.g., Java – float, doublee.g., Java – float, double PrecisionPrecision: the accuracy of the fractional part of a value: the accuracy of the fractional part of a value RangeRange: a combination of the ranges of fractions and : a combination of the ranges of fractions and
exponentsexponents
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Primitive Data Types –Primitive Data Types –Numeric Types (2)Numeric Types (2)
DecimalDecimal Store a fixed number of decimal digits (coded), with Store a fixed number of decimal digits (coded), with
decimal point at a fixed positiondecimal point at a fixed position BCD (Binary Coded Decimal)BCD (Binary Coded Decimal) Advantage: accuracy (e.g., 0.1 represented in BCD Advantage: accuracy (e.g., 0.1 represented in BCD
vs. Floating-point)vs. Floating-point) Disadvantages: limited range, wastes memoryDisadvantages: limited range, wastes memory
BooleanBoolean Could be implemented as bits, but often as bytesCould be implemented as bits, but often as bytes Advantage: readabilityAdvantage: readability
CharacterCharacter Stored as numeric codings (e.g., ASCII, Unicode)Stored as numeric codings (e.g., ASCII, Unicode)
* AW Lecture Notes
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Character String TypesCharacter String Types
Character StringCharacter String: a sequence of characters: a sequence of characters Design issues:Design issues:
Is it a primitive type or just a special kind of array?Is it a primitive type or just a special kind of array?e.g., Java – the String class, C – character arrays (char *str)e.g., Java – the String class, C – character arrays (char *str)
Is the length of strings static or dynamic?Is the length of strings static or dynamic? Static length stringsStatic length strings – e.g., Java, Fortran – e.g., Java, Fortran Limited dynamic length stringsLimited dynamic length strings – e.g., C (sizeof vs. strlen) – e.g., C (sizeof vs. strlen) Dynamic length stringsDynamic length strings – e.g., JavaScript, Perl – e.g., JavaScript, Perl
Operations:Operations: AssignmentAssignment, , ComparisonComparison (e.g., strcmp, >), (e.g., strcmp, >),
CatenationCatenation (e.g., strcat, +), (e.g., strcat, +), Substring referenceSubstring reference, , Pattern matchingPattern matching (e.g., indexOf, matches) (e.g., indexOf, matches)
* AW Lecture Notes
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Implementation of String TypesImplementation of String Types
Static lengthStatic length - compile-time descriptor - compile-time descriptor Limited dynamic lengthLimited dynamic length - may need a - may need a run-time run-time
descriptordescriptor for length (C and C++ use ‘ for length (C and C++ use ‘\0\0’ to indicate the ’ to indicate the end of the string)end of the string)
Dynamic lengthDynamic length - need run-time descriptor; - need run-time descriptor; allocation/deallocationallocation/deallocation is the biggest implementation is the biggest implementation problemproblem
* AW Lecture Notes
Compile-time descriptor for static strings
Run-time descriptor for limited dynamic strings
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
User-Defined Ordinal TypesUser-Defined Ordinal Types
An An ordinal typeordinal type is one in which the range of is one in which the range of possible values can be easily associated with the possible values can be easily associated with the set of positive integersset of positive integerse.g., Java – int, char, booleane.g., Java – int, char, boolean
Enumeration TypesEnumeration Types: user-defined ordinal types in : user-defined ordinal types in which named constants (which named constants (enumeration constantsenumeration constants) ) are provided in the definitionare provided in the definitione.g., e.g., enumenum days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; days { Mon, Tue, Wed, Thu, Fri, Sat, Sun };
days myDay = Sat;days myDay = Sat; char *str = names[Tue];char *str = names[Tue];
C++, C#, Pascal, Ada support enumeration typesC++, C#, Pascal, Ada support enumeration types Improve Improve readabilityreadability and and reliabilityreliability (restricting ranges) (restricting ranges)
Spring 2005 21
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Design Issues of User-Defined Design Issues of User-Defined Ordinal TypesOrdinal Types
Reuse of constants (Reuse of constants (overloaded literalsoverloaded literals)) e.g., e.g., enumenum weekendDays { Sat, Sun }; weekendDays { Sat, Sun }; ? ? The type of an occurrence of a constant needs The type of an occurrence of a constant needs
to be determined based on its contextto be determined based on its context Ada supports overloaded literalsAda supports overloaded literals
Coercion to integerCoercion to integer e.g., e.g., myDay++; myDay++; ??
myDay = 4;myDay = 4; ? ? myDate = (days)4;myDate = (days)4; ? ? C++ enumeration types are coerced to integerC++ enumeration types are coerced to integer
Spring 2005 22
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Subrange Types (Subtypes)Subrange Types (Subtypes)
Contiguous sequences of an ordinal typeContiguous sequences of an ordinal typee.g., e.g., subtypesubtype Index Index isis Integer Integer rangerange 1..100; 1..100;
typetype Days Days isis ( Mon, Tue, Wed, Thu, Fri, Sat, ( Mon, Tue, Wed, Thu, Fri, Sat, Sun);Sun);
subtypesubtype Weekdays Weekdays isis Days Days rangerange Mon..Fri; Mon..Fri; Pascal and Ada support subrange typesPascal and Ada support subrange types Subtypes are not new types, just constrained Subtypes are not new types, just constrained
existing types (so they are compatible); c.f., Derived existing types (so they are compatible); c.f., Derived TypesTypese.g., e.g., typetype Derived_Int Derived_Int is newis new Integer Integer rangerange 1..100; 1..100;
subtypesubtype Subrange_Int Subrange_Int isis Integer Integer rangerange 1..100; 1..100;
Enhance Enhance readabilityreadability and and reliabilityreliability
Spring 2005 23
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Array TypesArray Types
ArrayArray: an aggregate of : an aggregate of homogeneoushomogeneous data data elementselements in which an individual in which an individual element is element is identified by its position (identified by its position (subscriptsubscript or or indexindex))
IndexingIndexing: a mapping from indices to elements: a mapping from indices to elements e.g., e.g., A(2), A[2], *(A + 2)A(2), A[2], *(A + 2)
Subscript Types:Subscript Types: FORTRAN, C, Java – integer onlyFORTRAN, C, Java – integer only Pascal, Ada – any ordinal type (integer, boolean, char, Pascal, Ada – any ordinal type (integer, boolean, char,
enum)enum)
… …
00 11 n-1n-1 nn
An elementAn element
Subscripts (Indices)Subscripts (Indices)
A:A:
Spring 2005 24
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Categories of ArraysCategories of Arrays
Based on Based on subscript bindingsubscript binding and and binding to storagebinding to storage
Stack AreaStack Area(Local variables)(Local variables)
Static AreaStatic Area(Program code & non-local, (Program code & non-local,
static variables)static variables)
Heap AreaHeap Area(Dynamically (Dynamically
allocated/deallocated blocks)allocated/deallocated blocks)
A program space in A program space in the memorythe memory
……
… …
00 11 1818 1919
AAStatic Static (Fortran 77)(Fortran 77)
… …
00 11 n-1n-1 nn
AAStack-dynamicStack-dynamic
… …
00 11 n-1n-1 nn
AAFixed heap-dynamicFixed heap-dynamic
(Fortran 90, Java)(Fortran 90, Java)
… …
00 11 1818 1919
AAFixed stack-dynamic Fixed stack-dynamic
(Ada)(Ada)
… …
00 11 n-1n-1 xx
AAHeap-dynamicHeap-dynamic
(Perl, JavaScript)(Perl, JavaScript)
Spring 2005 25
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Other Design Issues of ArraysOther Design Issues of Arrays
Number of subscripts (Number of subscripts (DimensionDimension)) FORTRAN I allowed up to threeFORTRAN I allowed up to three FORTRAN 77 allows up to sevenFORTRAN 77 allows up to seven Others - no limitOthers - no limit
Array Initialization Array Initialization A list of valuesA list of values – e.g. (C), – e.g. (C), intint stuff [] = {2, 4, 6, 8}; stuff [] = {2, 4, 6, 8}; Positioned valuesPositioned values – e.g. (Ada), – e.g. (Ada),
SCORE : SCORE : arrayarray (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), 3 (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), 3 =>(12, 30), =>(12, 30), othersothers => (0, 0)); => (0, 0));
Array OperationsArray Operations Assignment, Concatenation, Elemental ops. (+), etc.Assignment, Concatenation, Elemental ops. (+), etc. Intrinsic (library) operationsIntrinsic (library) operations (e.g., matrix ops) (e.g., matrix ops) APLAPL supports many array operations supports many array operations
Spring 2005 26
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Multi-dimensional ArraysMulti-dimensional Arrays
Rectangular ArrayRectangular Array Jagged ArrayJagged Array
Slices:Slices:Substructures of an arraySubstructures of an array
e.g., FORTRAN 90 INTEGER MAT (1:4, 1:4) MAT(1:4, 1) - the first column MAT(2, 1:4) - the second row
Spring 2005 27
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Implementation of Array TypesImplementation of Array Types
Access FunctionAccess Function: maps subscript expressions : maps subscript expressions to an address in the arrayto an address in the arrayaddr(A[k]) = addr(A[lbound]) + ((k - lbound) * ele_size);addr(A[k]) = addr(A[lbound]) + ((k - lbound) * ele_size);
Row major orderRow major order vs. vs. column major ordercolumn major order Compile-time descriptors:Compile-time descriptors:
Single-dimensioned
array
Multi-
dimensional array
Spring 2005 28
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Homework #4Homework #4
Write a simple Java program that includes:Write a simple Java program that includes: At least two At least two non-local variablesnon-local variables defined with defined with initializationinitialization At least two At least two static variablesstatic variables defined in different scopes defined in different scopes At least two At least two overwriting variablesoverwriting variables defined in different scopes defined in different scopes At least two accesses of At least two accesses of hidden variableshidden variables Two Two named constantsnamed constants, one with the , one with the static value bindingstatic value binding, and the , and the
other with the other with the dynamic value bindingdynamic value binding
Add comments to indicate where those variables areAdd comments to indicate where those variables are Explain the Explain the static scopesstatic scopes of the variables of the variables Explain the Explain the lifetimeslifetimes of the variables of the variables Explain the Explain the reference environmentsreference environments at three different at three different
locations in the programlocations in the program
Due by March 31stDue by March 31st