concepts of programming languages (750321) files/cs/750321le.pdf · concepts of programming...

252
Concepts of Programming Languages 1 Concepts of Programming Languages (750321) A module For students in Departments CS, CIS, SE, ACS Faculty of IT / Philadelphia University Second Semester 2006/2007 A-PDF MERGER DEMO

Upload: dinhcong

Post on 30-Jun-2018

267 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 1

Concepts of Programming Languages (750321)

A module For students in DepartmentsCS, CIS, SE, ACS

Faculty of IT / Philadelphia University

Second Semester 2006/2007

A-P

DF

ME

RG

ER

DE

MO

Page 2: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 2

Concepts of Programming Languages(750321)

Lecturer: Dr. Nadia Y. Yousif

Email: [email protected]@hotmail.com

Room: IT 332

Page 3: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 3

Course Outline

AimsObjectivesAssessment and Passing the SubjectLectures and Tutorial classesLecturer and consultationRecommended reading

Page 4: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 4

Aims of this moduleTo provide students with a framework for thinking about programming languages.To learn different concepts of programming languages.To be able to learn new programming languages.To be able to select which programming language is most appropriate for a particular problem.

Page 5: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 5

Course Objectives

Understand different programming paradigms.Understand the syntax and semantics of programming languages.The ability of designing new programming language.The ability to develop different projects using different programming languages.

Page 6: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 6

Assessment and Passing

There are three assessment components:- Two midterm exams worth 15% of the marks

each- Course work worth 20% of the marks- Final exam worth 50%

You need to achieve an overall mark of 50% to pass the course.

Page 7: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 7

Lectures and Practice Classes

Lectures will be held at:14:10–15:10 pm on Sunday, Tuesday, and

Thursday in Room 7408From the third week, tutorials will be given to be discussed in some of the class hoursStudents are expected to work on practice problems, or on their assignments on free labs

Page 8: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 8

Lecturer and ConsultationLecturer:Dr. Nadia Y. YousifFaulty of IT, Room 332, Phone Ext: 544email: [email protected]

ConsultationThe primary time for consultation is during the tutorial classesOther consultation at the office hours (in room 332) on: (Sun, Tue, Thu) 12:00 – 13:00

(Mon, Wed) 13:45 – 15:15

Page 9: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 9

Recommended Reading

The text book is:R. Sebesta, Concepts of Programming Languages, Addison Wesley, 5th Edition, 2002

The following is other good reference:Terrence W. Pratt, Programming Languages: Design and Implementation, Prentice-Hall, 2002Note: Most of the slides presented in the lectures are from Sebesta reference

Page 10: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 10

Chapter OnePreliminaries, including

Why study PL concepts?Programming domainsPL evaluation criteriaWhat influences PL design?Tradeoffs faced by programming languagesImplementation methodsProgramming environments

Page 11: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 11

Why study ProgrammingLanguage Concepts?

Increased capacity to express programming conceptsImproved background for choosing appropriate languagesIncreased ability to learn new languagesUnderstanding the significance of implementationIncreased ability to design new languagesOverall advancement of computing

Page 12: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 12

Programming Domains

Scientific applications: (using Fortran, Algol 60)

Business applications: (using COBOL)

Artificial intelligence: (using LISP)

Systems programming: (using C in programming the UNIX operating system)

Scripting languages: (using Perl, Javascript)

Special purpose languages

Page 13: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 13

Language Evaluation Criteria

ReadabilityWritabilityReliabilityCostEtc…

Page 14: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 14

Evaluation Criteria: Readability

How is it for one to read and understand programs written in thePL?

Arguably the most important criterion!Factors effecting readability include

- Overall simplicityToo many features is bad OrthogonalityMakes the language easy to learn and readMeaning is context independent

- Control statements- Data type and structures- Syntax considerations

Page 15: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 15

Evaluation Criteria: Writability

How easy is it to write programs in the language?

Factors affecting writability:Simplicity and orthogonalitySupport for abstractionExpressivityFit for the domain and problem

Page 16: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 16

Evaluation Criteria: Reliability

Factors:- Type checking- Exception handling- Aliasing- Readability and writability

Page 17: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 17

Evaluation Criteria: Cost

Categories:Programmer trainingSoftware creationCompilationExecutionCompiler costPoor reliabilityMaintenance

Page 18: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 18

Evaluation Criteria: others

PortabilityGeneralityWell-definednessEtc…

Page 19: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 19

Language Design InfluencesComputer Architecture

-We use imperative languages, at least in part, because we use von Neumann machines

- John von Neumann is generally considered to be the inventor of the "stored program" digital computer - the class to which most of today's computers belong.

- CPU+memory which contains both program and data

-Focus on moving data and program instructions between registers in CPU to memory locations

Page 20: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 20

Language Design Influences: Programming Methodologies

1950s and early 1960s: Simple applications; worry about machine efficiencyLate 60s: People efficiency became important; readability, better control structures. maintainabilityLate 70s: Data abstractionMiddle 80s: Object-oriented programming95-today: distributed programs, the Web

Page 21: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 21

Language Categories

The big four:Imperative or procedural (e.g. Fortran, C)Functional (e.g. Lisp, ML)Rule-based (e.g. Prolog)Object-oriented (e.g. Smalltalk, Java)

Others:Scripting (e.g. Perl, Tcl/Tk)Constraint (e.g. Eclipse)

Page 22: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 22

Language Design Trade-offs

Reliability versus cost of executionAda, unlike C, checks all array indices to ensure proper range.

Writability versus readability(2 = 0 +.= T o.| T) / T <- iN is an APL one liner that

produces a list of the prime numbers from 1 to N inclusive.

Flexibility versus safetyC, unlike Java, allows one to do arithmetic on

pointers.

Page 23: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 23

Implementation methods

Direct execution by hardware ( e.g., machine language)Compilation to another language ( e.g., C)Interpretation

Direct execution by software (e.g., csh, Lisp (traditionally))

Hybrid Compilation to another language (aka bytecode) which is then interpreted (e.g., Java, Perl)

Page 24: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 24

Implementation issues

Complexity of compiler/interpreterSpeed of translationSpeed of executionPortability of translated codeCompactness of translated codeDebugging ease

compile hybrid interpret

Page 25: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 25

Programming Environments

The collection of tools used in software development, often including an integrated editor, debugger, compiler, collaboration tool, etc.Examples:

UNIX -- Operating system with tool collectionEMACS – a highly programmable text editorBorland C++ -- A PC environment for C and C++Smalltalk -- A language processor/environmentMicrosoft Visual C++ -- A large, complex visual

environmentYour favorite Java environment: Jbuilder, J++, …

Page 26: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Chapter Two

Topics to cover here:– Introduction – Variables (Names)– The Concept of Binding– Type Checking

Page 27: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Introduction

• Imperative Programming Languages are abstractions of the underlying Von Neumann computer architecture.

• The two primary components of this architecture are memory and processor.

• The abstractions in a language for the memory cells of the machine are variables.

• A variable has attributes: name, address, value, type, lifetime,scope.

• The design of data types in a language requires many issues to be considered:

- scope and lifetime of variables,- type checking and initialization.

Page 28: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Variable Attributes

1) Names (or identifiers)• They are the main attribute of variables.

• The primary design issues for names are:- What is the maximum length of a name?- Can connector characters be used in names?- Are names case sensitive?- Are the special words reserved word or

keywords?

Page 29: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Name Form

• A name is a string of characters used to identify some entity ina program.

• Some name forms in PLs:- In early PL, single-character names are used

(as in mathematics)- In Fortran I, Fortran 77, names are restricted to beof length up to 6 characters

- In Fortran 90, C, names can be up to 31 characters- In Java, Ada and C++, names have no limits on their length;

but implementers of these languages put some limit on names to simplify the maintenance of the symbol tableduring compilation.

Page 30: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Name Form .. Cont.

• In some languages, e.g. Java, C, C++, names are case sensitive.

• For example, the following 3 names are distinct: Length, LENGTH, length

• This can be a problem of writability rather than readability.

Page 31: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Special Words• Special words in PLs are used to make programs more

readable.1) A Keyword:• It is a word of a PL that is special only in certain context.• Example: the word REAL in Fortran language

- It is considered as a keyword as in a declarativestatement (e.g. REAL salary)- It is considered as variable (name) as in an assignment

(e.g. REAL = 3.5)• The program reader must recognize the difference between

names and special words by context.• Redefining keywords can lead to readability problem.

Page 32: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Special Words .. Cont.2) A Reserved word• It is a special name that cannot be used as a name.• Reserved words are better than keywords.

3) Predefined names• They are between reserved words and user-defined

names.• They have predefined meaning but can be redefined by

the user.• Example: the built-in data type names in Ada, such as

INTEGER and FLOAT, are predefined.• The definitions of the predefined names in Pascal and

Ada must be visible to the compilers of those language because of their compile-time type checking.

Page 33: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Address

• The address of a variable is the memory address with which it is associated.

• In many PLs, it is possible for the name to be associated with different addresses at different places and at different times in the program.

• Example: A program can have two subprograms, sub1 and sub2, each of which defines a variable named sum. The reference to sum in sub1 is unrelated to the reference to sum in sub2.

Page 34: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Address .. Cont.

• The address of a variable is sometimes called its l-value, because that is what is required when a variable appears in the left hand side of an assignment statement .

• When more than one variable name can be used to access a single memory location, the names are called aliases.

• For example, if variables A and B are aliases, any change to A also changes B and vice versa.

• Aliasing makes program verification more difficult.

Page 35: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Type

• The type of a variable determines the range of values the variable can have and the set of operations that are defined for values of the type.

• Example• In Fortran, the type INTEGER specifies

- a value range of -32,768 to 32,767- arithmetic operations: +, -, *, / - with some library functions such as function for

absolute value.

Page 36: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Value• The value of a variable is the contents of the memory

cell or cells associated with the variable.• It is convenient to think of computer memory in term

of abstract cells rather than physical cells.• For example, a floating-point value may occupy 4

physical bytes in a particular language, we think of a floating-point value as occupying a single abstract memory cell.

• A variable’s value is sometimes called r-valuebecause it is what is required when the variable is used on the right side of an assignment statement.

Page 37: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

The Concept of Binding

• A binding is an association, such as between an attribute and an entity or between an operation and a symbol.

• A Binding time is the time at which binding takes place.• Bindings can take place at:

- language design time- language implementation time- compile time- link time- load time- run time

Page 38: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

The Concept of Binding .. Cont.

• Example• Consider the following piece of C++ program:

int count;…count = count + 5;

• Some of the bindings and their binding times for this assignment statement are as follows:

Page 39: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

The Concept of Binding .. Cont.

• Set of possible types for count: bound at language design time.

• Type of count: bound at compile time.• Set of possible values of count: bound at compiler design

time.• Value of count: bound at execution time with this statement.• Set of possible meanings for the operator symbol +: bound at

language definition time.• Meaning of the operator symbol + in this statement: bound at

compile time.• Internal representation of the literal 5: bound at compiler

design time.

Page 40: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

Binding of Attributes to Variables

• Bindings made before run time are called static.

• Bindings made during run time are called dynamic.

• Note that many bindings are made before compile time. For example, while is bound by the language definition.

Page 41: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

Type Binding• A variable must be bound to a data type before referencing it in a

program.• Types can be specified statically through explicit or implicit

declarations.

• Variable declarations- An explicit declaration declares names and specifies types for them.- An implicit declaration is a means of associating variables with types through default conventions. In this case, the first appearance of a variable name in a program constitutes its implicit declaration (as in Fortran: identifiers begin with one of the letters I, J, K, L, M, or N are implicitly of type INTEGER; otherwise, they are implicitly real.- Both explicit and implicit declarations create static bindings to types.

Page 42: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

Type Binding .. Cont.• Note that x and y have no ``meaning'' in the statement:

y = 5 * x ;• Meaning may be provided by placing the statement in an

appropriate context as follows:int y;int x;x = 6;y = 5 * x;

• The declaration ``int x;'' binds x. • We say that x is bound by that declaration (and likewise y for

its declaration). • Such statements are called name binding statements, or simply

binders. In many imperative languages, name binders are considered separate statements, but this is not true in general.

Page 43: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

18

Free and Bound Variable Occurrences• Notions of free and bound variable occurrences depend upon the

surrounding context, which may include binders. • A free occurrence of an identifier is a use which has no matching

binding: y = 5 * x; // Free occurrences of x and y

• A declaration occurrence of an identifier is one which declares it: int y; // declaration occurrence of y

• A bound occurrence of an identifier is a use which has a matching declaration:

int y; // Declaration occurrence of yint x; // Declaration occurrence of xx=6; // Bound occurrence of xy = 5 * x; // Bound occurrences of x and y

Page 44: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

19

Dynamic Type Binding

• In Dynamic binding, the type is not specified by a declaration statement.

• The variable is bound to a type when it is assigned a value in an assignment statement.

• When the assignment statement is executed, the variable on the left side of the assignment is bound to the type of the value, variable, or, expression on the right side of the assignment.

• APL, NOBOL4, and JavaScript use dynamic binding of variables to types

Page 45: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

20

Dynamic Type Binding .. Cont.

• The advantage of dynamic binding of variables to types is that it provides a great deal of programming flexibility.

• The disadvantages of dynamic type binding are:1- The errors cannot be detected at compile time.2- The cost of implementing dynamic attribute

binding is considerable, particularly in executiontime.

- Type checking must be done at run time;- Every variable must have a descriptor associated with itto maintain the current type.

- The storage used for the value of a variable must be ofvarying size.

Page 46: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

21

Type Checking• Type checking is the activity of ensuring that the operands

of an operator are of compatible types.• A Compatible type is one that is either legal for the

operator or is allowed under language rules to be implicitly converted by compiler-generated code to a legal type. This automatic conversion is called a coercion.

• A type error is the application of an operator to an operand of an inappropriate type.

• Type checking could be:- Static type checking where variables are bound to

types statically (at compile-time).- Dynamic type checking where type binding is done at

run-time.

Page 47: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

22

Strong Typing

• A strongly typed language is one in which each name in a program in the language has a single type associated with it, and that type is known at compile time.

• The weakness of this definition is that it ignores the possibility that, although a variable’s type may be known, the storage location to which it is bound may store values of different types at different times.

• Hence, a PL to be strongly typed, the type error should always be detected.

• The importance of strong typing is to detect all misuses of variables that result in type errors.

Page 48: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

23

Strong Typing .. Cont.

• Fortran is not strongly types because the relationship between actual and formal parameter is not type checked.

• Pascal is nearly strongly typed, but it fails in it design of variant records because it allows omission of the tag that stores the current type of a variable, which provides the means of checking for the correct value types.

• C and C++ are not strongly typed because they allow functions for which parameter are not type checked.

• Java is strongly typed. Types can be explicitly cast, which could result in a type error.

Page 49: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Chapter Three

Topics to cover here:• Scope

- Static Scope- Blocks- Dynamic Scope

• Scope and Lifetime• Referencing Environments• Named Constants• Variable Initialization

Page 50: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Scope

• The scope of program variable is the range of statements in which the variable is visible.

• A variable is visible in a statement if it can be referenced in that statement.

• The scope rules of a language determine how a particular occurrence of a name is associated with a variable.

• A variable is local in a program unit or block if it is declared there.

• The non-local variables of a program unit or block are those that are visible within the program unit or block but are not declared there.

Page 51: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Static Scope• ALGOL 60 language introduced the method of binding names

to non-local variables, called static scoping, which has been copied by most subsequent imperative languages and many non-imperative languages as well.

• Static scopes in imperative languages are associated with program unit definition.

• To connect a name reference to a variable, you (or the compiler) must find the declaration

• Search process: search declarations, first locally, then in increasingly larger enclosing scopes, until one is found for thegiven name

• Enclosing static scopes (to a specific scope) are called itsstatic ancestors; the nearest static ancestor is called a static parent

• In most languages, subprograms create their own scopes.• In Pascal, Ada, and JavaScript, subprograms can be nested

inside subprograms which can create a hierarchy of scope in a program.

Page 52: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Static Scope• Consider the following Pascal procedure:

procedure big;var x : integer;procedure sub1;

begin { sub1 } … x …

end; { sub1 }procedure sub2;

var x : integer ;begin { sub2 }

…end; { sub2 }

begin { big }…

end; { big }

Page 53: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Static Scope

• Under static scoping, the reference to the variable x in sub1 is to the x declared in the procedure big.

• The search for x begins in the procedure in which the reference occurs, sub1.

• The search continues in the static parent of sub1, big, where the declaration of x is found.

• In languages that use static scoping, some variable declarations can be hidden from some subprograms.

Page 54: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Static Scope

• Consider the following Pascal program:program main;

var x : integer;procedure sub1;

var x : integer;begin { sub1 }

… x …end { sub1 }

begin { main }…

end. { main }

Page 55: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Static Scope• In the previous example, the reference to x in sub1 is to sub1’s

declared x. The x of the main program is hidden from the code of sub1.

• In general, a declaration for a variable hides any declaration of a variable with the same name in a larger enclosing scope.

• C and C++ do not allow subprograms to be nested inside other subprogram definitions, but they have global variables, which are declared outside any subprogram definition.

• Local variables can hide global variables as in Pascal.• In C++, a global variable can be accessed using the scope

operator (::). For example, if x is a global that is hidden in asubprogram by a local named x, the global could be referenced as ::x

Page 56: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Blocks• In ALGOL 60, the concept of block was introduced.• A Block is a method of creating static scopes inside program

units• Inside a block, it is allowed to declare local variables whose

scope is minimized.• These variables have their storage allocated when the block is

entered and deallocated when the block is exited.• Examples:• C and C++: for (...)

{ int index;...

}• In Ada, blocks are specified with declare clauses, as in

declare TEMP : integer;begin

…end ;

Page 57: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Blocks

• Pascal and Modula-2 are block-structured languages but do not include nonprocedural blocks.

• C, C++, and Java allow any compound statementsto have declarations and define a new scope. Such compound statements are blocks.

• Scopes created by blocks are treated like those created by subprograms.

• References to variables in a block that are not declared there are connected to declarations by searching enclosing scopes in order of increasing size.

Page 58: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Blocks

• C++ and Java allow variable definitions to appear anywhere in functions. The scope of the variable is from its definition statement to the end of the function.

• The for statements of C++ and Java allow variable definitions in their initialization expressions. The scope is restricted to the for construct.

• The class and method definitions in object-oriented languages also create nested static scope.

Page 59: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Consider the example:Assume MAIN calls A and B

A calls C and DB calls A and E

MAINA

C

D

BE

MAIN

A B

C D E

MAIN MAIN

A B A B

C D E C D E

Evaluation of Static Scoping

Page 60: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Evaluation of Static Scoping

• Suppose the specification is changed so that D must now access some data in B

• Solutions:1. Put D in B (but then C can no longer call it and D cannot

access A's variables)2. Move the data from B that D needs to MAIN (but then all

procedures can access them)

• Same problem for procedure access!• Overall: static scoping often encourages many globals

Page 61: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

Dynamic Scope

• Dynamic scope is based on calling sequences of program units, not their textual layout (temporal versus spatial)

• References to variables are connected to declarations by searching back through the chain of subprogram calls that forced execution to this point

Page 62: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

MAIN- declaration of x

SUB1- declaration of x -...call SUB2...

SUB2...- reference to x -...

...call SUB1...

MAIN calls SUB1SUB1 calls SUB2SUB2 uses x

Dynamic ScopeStatic scoping - reference to x is to MAIN's x

Dynamic scoping - reference to x is to SUB1's x

Example:

Page 63: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

- Advantage: convenience- Disadvantage: poor readability……………………………………………………

Scope and Lifetime• Scope and lifetime are sometimes closely related, but

are different concepts!!• Consider a static variable in a C or C++ function

Evaluation of Dynamic Scoping

Page 64: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

Scope and Lifetime• ExampleConsider the following C++ functions:

void printheader ( ){ … } // end of printheader

void compute ( ){ int sum ;

…printheader ( );

} // end of compute• The scope of the variable sum

- is completely contained within compute function;- it does not extend to the body of the function printheader, although printheader execute in the midst of the execution of compute.

• The lifetime of sum- extends over the time during which printheader executes- Whatever storage location sum is bound to before the call to printheader, that binding will continue during and after the execution of printheader

Page 65: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

Def: The referencing environment of a statement is the collection of all names that are visible in the statement

- In a static scoped language, the referencing environment is the local variables plus all of the visible variables in all of the enclosing scopes

- A subprogram is active if its execution has begun but has not yet terminated

- In a dynamic-scoped language, the referencing environment is the local variables plus all visible variables in all active subprograms

Referencing Environments

Page 66: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

18

Referencing Environments in a Static Scoped Language

• In Pascal, scopes are created only by procedure definitions (It is a static scoped language).

• The referencing environment of a statement in Pascal includes:- local variables- all of the variables declared in the procedures in

which the statement is nested- variables declared in the main program

Page 67: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

19

Referencing Environments: An ExampleProgram example ;

var a , b : integer ;…procedure sub1;

var x , y : integer ;begin { sub1 }

... -1end; { sub1 }

procedure sub2 ;var x : integer ;…procedure sub3 ;

var x : integer ;begin { sub3 }… -2

end; { sub3 }begin { sub2 }

… -3end; { sub2 }

begin { example }… -4

end. { example }

Page 68: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

20

Referencing Environments: An Example

• The referencing environment of the indicated points are a follows:

Point Referencing Environment1 x and y of sub1, a and b of example2 x of sub3, (x of sub2 is hidden), a and b of example3 x of sub2, a and b of example4 a and b of example

Page 69: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

21

Referencing Environments in a Dynamic Scoped Language: An Example

Assume that main calls sub2 and sub2 calls sub1 in this example:

void sub1( ){ int a , b ;

… -1} // end of sub1

void sub2 ( ){ int b , c ;

… -2sub1 ( );

} // end of sub2void main ( ){ int c , d ;

… -3sub2 ( );

} // end of main

Page 70: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

22

Referencing Environments in a Dynamic Scoped Language: An Example

The referencing environment of the indicated point are as follows:

Point Referencing Environment1 a and b of sub1, c of sub2, d of main,

(c of main and b of ub2 are hidden)2 b and c of sub2, d of main, (c of main is hidden)3 c and d of main

Page 71: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

23

Named Constant and Variable Initialization

Def: A named constant is a variable that is bound to a value only when it is bound to storage

- Advantages: readability and modifiability

The binding of values to named constants can be either static (called manifest constants) or dynamicLanguages:

Pascal: literals onlyModula-2 and FORTRAN 90: constant-valued expressionsAda, C++, and Java: expressions of any kind

Def: The binding of a variable to a value at the time it is bound to storage is called initializationInitialization is often done on the declaration statement

e.g., AdaSUM : FLOAT := 0.0;

Page 72: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

24

Named Constant: An Example• Consider the following Java program segment:

void example ( ){ int [ ] intList = new int [100] ;

String [ ] strList = new String[100] ;…for ( index = 0 ; index < 100 ; index ++ ){ … }for ( index = 0 ; index < 100 ; index ++ ){ … }average = sum / 100 ;…

}

Page 73: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

25

Named Constant: An Example• When the previous program is modified to deal with different

number of data values, all occurrences of 100 must be changed. This can be tedious and error-prone

• The program can be modified to have named constant:

void example ( ){ final int len = 100 ;

int [ ] intList = new int [len] ;String [ ] strList = new String [len] ;…for ( index = 0 ; index < len ; index ++ ){ … }for ( index = 0 ; index < len ; index ++ ){ … }average = sum / len ;… }

Page 74: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Chapter Four

Topics to cover here:• Primitive Data Types• Character String Types• User-Defined Ordinal Types• Array Types

Page 75: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Data Types: An IntroductionEvolution of Data Types:• FORTRAN I (1956) - INTEGER, REAL, arrays

…• Ada (1983) - User can create a unique type for every category

of variables in the problem space and have the system enforce the types

• All data types need descriptors.

• Def: A descriptor is the collection of the attributes of a variable

Design Issues for All Data Types:1. What is the syntax of references to variables?2. What operations are defined and how are they specified?

Page 76: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Primitive Data TypesPrimitive Data Types are those not defined in terms of other data types

1- Integer- Almost always an exact reflection of the hardware, so the mapping is

trivial- There may be as many as eight different integer types in a language.

2- Floating Point- Model real numbers, but only as approximations- Languages for scientific use support at least two floating-point types;

sometimes more- Usually exactly like the hardware, but not always; some languages

allow accuracy specs in code e.g. (Ada)

• type SPEED is digits 7 range 0.0..1000.0;• type VOLTAGE is delta 0.1 range -12.0..24.0;

Page 77: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Exponent Fraction

Exponent Fraction

Primitive Data Types.. Cont.• The floating point formats

(a) Single precision8 bits 23 bits

sign bit

(b) Double precision11 bits 52 bits

sign bit

Page 78: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Primitive Data Types .. Cont.• Decimal

- For business applications (money)- Store a fixed number of decimal digits (coded)- Advantage: accuracy- Disadvantages: limited range, wastes memory

3- Boolean- Could be implemented as bits, but often as bytes- Advantage: readability

Page 79: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Character String Types

- Values are sequences of characters

Design issues:

1. Is it a primitive type or just a special kind of array?2. Is the length of objects static or dynamic?

Operations:- Assignment - Comparison (=, >, etc.) - Concatenation- Substring reference- Pattern matching

Page 80: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Character String Types .. Cont.

Examples:- Pascal

- Not primitive; assignment and comparison only (of packed arrays)

- Ada, FORTRAN 77, FORTRAN 90 and BASIC- Somewhat primitive- Assignment, comparison, concatenation, substring

reference - FORTRAN has an intrinsic for pattern matching

Page 81: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Character String Types .. Cont.

Example of String operations:1- In Ada:

N := N1 & N2 (concatenation)N (2..4) (substring reference)

2- In C and C++- Not primitive- Use char arrays and a library of functions that provide operations (e.g. string.h)

3- SNOBOL4 (a string manipulation language)- Primitive- Many operations, including elaborate pattern matching

4- Perl- Patterns are defined in terms of regular expressions- A very powerful facility!

5- Java - String class (not arrays of char)

Page 82: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

String Length Options

1. Static – as in FORTRAN 77, Ada, COBOLe.g. (FORTRAN 90)

CHARACTER (LEN = 15) NAME;

2. Limited Dynamic Length – as in C and C++actual length is indicated by a null character

3. Dynamic – as in SNOBOL4, Perl

Page 83: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Evaluation of Character String Types

• Aid to writability- As a primitive type with static length, they are

inexpensive to provide--why not have them?

- Dynamic length is nice, but is it worth the expense?

Page 84: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Implementation of Strings

- For Static length strings, a compile-time descriptor is needed such as:

- For Limited Dynamic length strings, a run-timedescriptor for length may be needed (but not in C and C++)

Static stringLength

Address

Limited dynamic stringMaximum lengthCurrent length

Address

Page 85: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Implementation of Strings

- The limited dynamic strings of C and C++ do not require run-time descriptor because the end of a string is marked with the null character.

- For Dynamic length strings, a run-time descriptor is needed. In this case,

- allocation/deallocation is the biggest - implementation problem- the dynamic allocation can be in two ways:

1- Strings can be stored in a linked list2- Strings are stored in adjacent storage cells.

- The allocation and deallocation processes are simple in the linked list implementation (but string operations are slowed by the required pointer chasing).

- Using adjacent cells requires less storage and faster string operations.

Page 86: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

User Defined Ordinal Types• An ordinal type is one in which the range of possible values

can be easily associated with the set of positive integers.• In Pascal and Ada, the primitive ordinal types are: integer,

char, Boolean.• In many languages, users can define two kinds of ordinal

types: enumeration and subrange.

1- Enumeration Type - one in which the user enumerates all of the possible values, which are symbolic constants.e.g. in Ada, enumeration type is declared as follows: type DAYS is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);

• Design Issue: Should a symbolic constant be allowed to be in more than one type definition?

Page 87: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

1- Enumeration Types• Examples:- Pascal - cannot reuse constants; they can be used for array subscripts, for

variables, case selectors; NO input or output; can be compared. For example,

type colortype = (red, blue, green, yellow);var color : colortype;…color := blue;if color > red …

The Boolean expression of the if will evaluate to true.

- Ada - constants can be reused (overloaded literals); disambiguate with context or type_name (one of them); can be used as in Pascal; CAN be input and output.

- C and C++ - like Pascal, except they can be input and output as integers.

- Java- the enumeration types are classes that implement the Enumeration interface.

Page 88: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

Evaluation of Enumeration Types

• Aid to readability. - Named values are easily recognized.- e.g. no need to code a color as a number

• Aid to reliability.- e.g. compiler can check operations and ranges of values

Page 89: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

2. Subrange Type• Subrange type is an ordered contiguous subsequence of an

ordinal type. For example, 12 .. 15 is a subrange of integer type

• Design Issue: How can they be used?

• Examples:- PascalSubrange types behave as their parent types; can be used as for variables and array indicese.g. type

pos = 0 .. MAXINT;index = 1 .. 100;

Page 90: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

2. Subrange Type .. Cont.- Ada- Subranges are not new types just constrained existing types (so they are compatible). - They are included in the class of types called subrange.- They can be used as in Pascal, plus case constants- e.g.

subtype WEEKDAYS is DAYS range Mon .. Fri ;subtype INDEX is INTEGER range 1 .. 100 ;

Evaluation of Subrange Types• Aid to readability• Aid to reliability - restricted ranges add error detection

Page 91: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

18

Implementation of user-defined ordinal types

- Enumeration types are implemented as integers

- Subrange types are the parent types with code inserted (by the compiler) to restrict assignments to subrange variables

Page 92: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

19

Array Types• An array is an aggregate of homogeneous data elements in

which an individual element is identified by its position in the aggregate, relative to the first element.

• Design Issues:1. What types are legal for subscripts?2. Are subscripting expressions in element references range

checked?3. When are subscript ranges bound?4. When does allocation take place?5. What is the maximum number of subscripts?6. Can array objects be initialized?7. Are any kind of slices allowed?

Page 93: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

20

Array and Indexes

• Indexing is a mapping from indices to elements:array_name (index_value_list) → an element

• Syntax of array references:- FORTRAN, PL/I, Ada use parentheses- Most others use brackets

• Subscript Types:- FORTRAN, C: int only- Pascal: any ordinal type (int, boolean, char, enum)- Ada: int or enum (includes boolean and char)- Java: integer types only

Page 94: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

21

Subscript Bindings and Array Categories

• Four Categories of Arrays (based on subscript binding and binding to storage)

1. Static: range of subscripts and storage bindings are statice.g. FORTRAN 77, some arrays in AdaAdvantage: execution efficiency (no allocation or deallocation)

2. Fixed stack dynamic: range of subscripts is statically bound, but storage is bound at elaboration timee.g. Pascal locals and, C locals that are not staticAdvantage: space efficiency

Page 95: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

22

Subscript Bindings and Array Categories

3. Stack-dynamic: range and storage are dynamic, but fixed from then on for the variable’s lifetimee.g. Ada declare blocks:

declareSTUFF : array (1..N) of FLOAT;begin...end;

Advantage: flexibility - size need not be known until the array is about to be used

Page 96: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

23

Subscript Bindings and Array Categories

4. Heap-dynamic: subscript range and storage bindings are dynamic and not fixede.g. In FORTRAN 90,- INTEGER, ALLOCATABLE, ARRAY (:,:) :: MAT

(Declares MAT to be a dynamic 2-dim array)- ALLOCATE (MAT (10, NUMBER_OF_COLS))

(Allocates MAT to have 10 rows andNUMBER_OF_COLS columns)

- DEALLOCATE MAT (Deallocates MAT’s storage)

- In APL & Perl, arrays grow and shrink as needed- In Java, all arrays are objects (heap-dynamic)

Page 97: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

24

Number of Subscripts in Arrays and Array Initialization

- FORTRAN I allowed up to three subscripts- FORTRAN 77 allows up to seven- C, C++, and Java allow just one, but elements can be arrays- Others - no limit

• Arrays are initialized by a list of values that are put in the array in the order in which the array elements are stored in memory

Examples:1. FORTRAN - uses the DATA statement, or put the values in / ... / on the

declaration2. C and C++ - put the values in braces; can let the compiler count them

e.g. int stuff [ ] = {2, 4, 6, 8};3. Ada - positions for the values can be specified

e.g. SCORE : array (1..5) of INTEGER := (1 => 3, 2 => 7, 3 => 12, others => 0);

Page 98: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

25

Array Operations• An array operation is one that operates on an array as a unit.1- FORTRAN 77 provides no array operation.2. Ada has array operations such as:

- assignment; RHS can be an aggregate constant or an array name- catenation (specified by & ); for all single-dimensioned

arrays- relational operators (= and /= only)

3. FORTRAN 90 has array operations called elemental because they are operations between pairs of array elements:- e.g. + between two arrays - intrinsic (subprograms) for a wide variety of array operations (e.g., matrix multiplication, vector dot product)

Page 99: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

26

Evaluation and Implementation of Arrays

Evaluation- Arrays are simple and have well developed.- The significance of using dynamic arrays and arrays

of subscripts that are of ordinal types

Implementation- Access function maps subscript expressions to an

address in the array - Row major (by rows) or column major order (by

columns)

Page 100: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

27

Implementation of Arrays- The access function for one-dimensional array

Suppose that list is an array of lower bound 1, and we want to access the element indexed by k. The access function is:address (list [k]) = address (list [1]) + (k-1)*element_size

Oraddress (list [k]) = (address (list [1])- element_size) +

( k * element_size )- The first operand of the + operation is the constant part (can

be computed before run time, if the element type is statically bound)

- The second operand is the variable part (can be computed at run-time)

Page 101: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

28

Implementation of ArraysThe access function for two-dimensional arrayTo access an element in an array of two dimensions of size n x m, say a[i, j], stored in row major, we have:

location(a[i, j]) = address(a[1, 1]) + ((((number of rows above the ith row) * (size of a row)) + (number of rows left of the jth column)) * element size)

That is:location (a[i, j]) = address(a[1, 1]) + (((i - 1) * n) +

(j - 1)) * element_size

Page 102: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Chapter Five

Topics to cover here:• Record Types• Union Types• Set Types• Pointer Types

Page 103: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Records

• A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names

• Design Issues:1. What is the form of references? 2. What unit operations are defined?

• Record Definition Syntax- COBOL uses level numbers to show nested records; - others use recursive definitions

Page 104: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Record Examples• In COBOL01 EMPLOYEE-RECORD.

02 EMPLOYEE-NAME.05 FIRST PICTURE IS X(20).05 MIDDLE PICTURE IS X(10).05 LAST PICTURE IS X(20).

02 HOURLY-RATE PICTURE IS 99V99.

Page 105: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Record Examples .. Cont.• In Ada

EMPLOYEE_RECORD :record

EMPLOYEE_NAME :record

FIRST : STRING (1..20);MIDDLE : STRING (1..10);LAST : STRING (1..20) ;

end record ;HOURLY_RATE : FLOAT ;

end record ;

• In C++struct employee{ int id ;

string name ;char gender ;float rate ;

};

Page 106: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Record Field References1. COBOL

field_name OF record_name_1 OF ... OF record_name_ne.g.

MIDDLE OF EMPLOYEE-NAME OF EMPLOYEE-RECORD

2. Others (dot notation)record_name_1.record_name_2. … record_name_n.field_namee.g.EMPLOYEE-RECORD.EMPLOYEE-NAME. MIDDLE

• Fully qualified referencesmust include all record names (as in COBOL, Ada)

• Elliptical references allow leaving out record names as long as the reference is unambiguous (as in COBOL, PL/I)

Page 107: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Record Field References• Pascal and Modula-2 provide a with clause to abbreviate

references.e.g. Code without with clause Code uses with clauseemployee.name := ‘Ali’ ; with employee doemployee.age := 42 ; begin employee.sex := ‘M’ ; name := ‘Ali’ ;employee.salary := 510.54 ; age := 42 ;

sex := ‘M’ ;salary := 510.54 ;

end ; { end of with }

Page 108: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Record Operations1. Assignment

- Pascal, Ada, and C allow it if the types are identical- In Ada, the RHS can be an aggregate constant

2. Initialization- Allowed in Ada, using an aggregate constant

3. Comparison- In Ada, = and /=; one operand can be an aggregate

constant4. MOVE CORRESPONDING

- In COBOL - it moves all fields in the source record tofields with the same names in the destination record

Page 109: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Comparing Records and Arrays

1. Access to array elements is much slower than access to record fields, because subscripts are dynamic (field names are static)

2. Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower

Page 110: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Implementation of Record TypesThe compile-time descriptor is as follows:(Note that the descriptor contains the offset address

relative to the beginning of the record. This used for field accesses).

AddressOffsetTypeName

.

.

.

OffsetTypeNameRecord

Field 1

Field 2

Page 111: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Unions

• A union is a type whose variables are allowed to store different type values at different times during execution

• Design Issues for unions:1. What kind of type checking, if any, must be done?2. Should unions be integrated with records?

Page 112: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Union Examples

1. FORTRAN - with EQUIVALENCE statement

2. C, C++ : there is the union construct

• The union in these languages is called free union: the programmer is allowed complete freedom from type checking in their use.

3. Pascal Union TypesType checking of unions requires that each union construct

includes a type indicator called tag or discriminant.

• Pascal has both discriminated and nondiscriminated unions• The discriminated union is called a record variant

Page 113: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Union Examplese.g. type shape = (circle, triangle, rectangle) ;

colors = (red, green, blue);figure =

recordfilled : boolean ;color : colors ;case form : shape of

circle : (diameter : real ) ;triangle : (leftside : integer ; rightside : integer ;

angle : real ) ;rectangle : (side1 : integer; side2 : integer ; )

end;

var f1 : figure;

Page 114: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

Union Examples

• You can access any field by the dot notation such as:case f1.form of

circle : writeln (‘Circle; diameter = ‘ , f1.diameter);rectangle :writeln (‘rectangle; sides are: ‘ , f1.side1, f1.side2);

end

• Problem with Pascal’s design: type checking is ineffective• Reasons:

a) User can create inconsistent unions (because the tag can be individuallyassigned)

b) The tag is optional! That is, Union could be a free union.

Consider the following:

Page 115: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

Union Examplestype figure =

record…

case shape ofcircle : (diameter : real ) ;triangle : (leftside : integer ; rightside : integer ;

angle : real ) ;rectangle : (side1 : integer; side2 : integer ; )

end ;

- The user and the system cannot determine the current variant type.If f1.diameter := 2.73, then there is no way to guard against incorrect references such as side := f1.leftside;That is, both f1.diameter and f1.leftside can be assigned and referenced at any time.

Page 116: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

Union Examples

4. Ada - discriminated unions- Reasons they are safer than Pascal & Modula-2:

a. Tag must be presentb. It is impossible for the user to create an inconsistent union

(because tag cannot be assigned by itself--All assignments to the union must include the tag value)

5. Java has neither records nor unions

Evaluation - potentially unsafe in most languages (not Ada)

Page 117: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

Union Implementation

• Discriminated unions are implemented by simply using the same address for every possible variant.

• In case of constrained variants in Ada language, a complete descriptor can be stored at compile time, because there I no variation.

• e.g.type NODE (TAG : BOOLEAN ) is

recordcase TAG is

when true => COUNT : INTEGER ;when false => SUM : FLOAT ;

end case;end record;

The descriptor of this type is as follows:

Page 118: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

Union Implementation

TAG

Address

OffsetBOOLEAN

Discriminated Union

falsetrue

INTEGER

COUNT

FLOAT

SUM

Case table

Name

Type

Name

Type

Page 119: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

18

Sets

• A set is a type whose variables can store unordered collections of distinct values from some ordinal type

• Design Issue:- What is the maximum number of elements in any set

base type?

• Examples:1. Pascal

- No maximum size in the language definition (notportable, poor writability if max is too small)

- Operations: union (+), intersection (*), difference (-),=, <>, superset (>=), subset (<=), in

Page 120: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

19

Sets .. Cont.

2. Modula-2 and Modula-3- Additional operations: INCL, EXCL, /

(symmetric set difference (elements in one but notboth operands))

3. Ada - does not include sets, but defines in as setmembership operator for all enumeration types

4. Java includes a class for set operations

Page 121: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

20

Set Example

type colors = (red, blue, green, yellow, orange, white, black);colorset = set of colors;var set1, set2 : colorset ;…set1 := [red, blue, white];set2 := [black, blue];

Page 122: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

21

Sets .. Cont.• Evaluation

- If a language does not have sets, they must be simulated, either with enumerated types or with arrays

- Arrays are more flexible than sets, but have much slower operations

• Implementation- Usually stored as bit strings and use logical

operations for the set operations.

Page 123: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

22

Pointers• A pointer type is a type in which the range of values consists of

memory addresses and a special value, nil (or null)

• Uses:1. Addressing flexibility2. Dynamic storage management

• Design Issues:1. What is the scope and lifetime of pointer variables?2. What is the lifetime of heap-dynamic variables?3. Are pointers restricted to pointing at a particular type?4. Are pointers used for dynamic storage management, indirect

addressing, or both?5. Should a language support pointer types, reference types, or both?

• Fundamental Pointer Operations:1. Assignment of an address to a pointer2. References (explicit versus implicit dereferencing)

Page 124: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

23

Problems with Pointers

1. Dangling pointers (dangerous)- A pointer points to a heap-dynamic variable that has

been deallocated

- Creating one:a. Allocate a heap-dynamic variable and set a

pointer to point at it

b. Set a second pointer to the value of the firstpointer

c. Deallocate the heap-dynamic variable, using thefirst pointer

Page 125: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

24

Problems with Pointers

2. Lost Heap-Dynamic Variables (wasteful)- A heap-dynamic variable that is no longer

referenced by any program pointer - Creating one:

a. Pointer p1 is set to point to a newly createdheap-dynamic variable

b. p1 is later set to point to another newly createdheap-dynamic variable

- The process of losing heap-dynamic variables iscalled memory leakage

Page 126: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

25

Examples of Pointers

1. Pascal: used for dynamic storage management only- Explicit dereferencing- Dangling pointers are possible (dispose)- Dangling objects are also possible

2. Ada: a little better than Pascal and Modula-2- Some dangling pointers are disallowed because dynamic

objects can be automatically deallocated at the end ofpointer's scope

- All pointers are initialized to null- Similar dangling object problem (but rarely happens)

Page 127: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

26

Examples of Pointers3. C and C++

- Used for dynamic storage management and addressing- Explicit dereferencing and address-of operator- Can do address arithmetic in restricted forms- Domain type need not be fixed (void * )

e.g. float stuff[100];float *p;p = stuff;

*(p+5) is equivalent to stuff[5] and p[5]*(p+i) is equivalent to stuff[i] and p[i]

- void * - can point to any type and can be type checked (cannot be dereferenced)

Page 128: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

27

Examples of Pointers4. FORTRAN 90 Pointers

- Can point to heap and non-heap variables- Implicit dereferencing- Special assignment operator for non-dereferenced references

e.g. REAL, POINTER :: ptr (POINTER is an attribute)ptr => target (where target is either a pointer or a

non-pointer with the TARGET attribute))

- The TARGET attribute is assigned in the declaration, as in:

INTEGER, TARGET :: NODE

Page 129: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

28

Examples of Pointers5. C++ Reference Types

- Reference type variable is a constant pointer that isimplicitly dereferenced

- Used for parameters- Advantages of both pass-by-reference and pass-by-value- e.g. int result = 0;

int &ref = result; // ref is a reference to result

6. Java - Only references- No pointer arithmetic- Can only point at objects (which are all on the heap)- No explicit deallocator (garbage collection is used)

- Means there can be no dangling references- Dereferencing is always implicit

Page 130: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

29

Evaluation of pointers

1. Dangling pointers and dangling objects are problems, as is heap management

2. Pointers are like goto's--they widen the range of cells that can be accessed by a variable

3. Pointers are necessary--so we can't design a language without them

Page 131: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

30

Memory Management• Memory management: identify unused, dynamically

allocated memory cells and return them to the heap.

• Approaches – Manual: explicit allocation and deallocation (C, C++)

( by new and delete procedures)- Automatic:

• Reference counters (modula2, Adobe Photoshop)• Garbage collection (Lisp, Java)

• Problems with manual approach:– Requires programmer effort– Programmer’s failures leads to space leaks and dangling

references/sharing– Proper explicit memory management is difficult and has

been estimated to account for up to 40% of development time!

Page 132: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

31

Solutions to Dangling Pointer Problem(1) Reference Counting

• Idea: - keep track how many references there are to a cell in

memory. - If this number drops to 0, the cell is garbage. - Store garbage in free list; allocate from this list

• Advantages– immediacy– resources can be freed directly– immediate reuse of memory possible

• Disadvantages– Can’t handle cyclic data structures– Bad locality properties– Large overhead for pointer manipulation

Page 133: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

32

Solutions to Dangling Pointer Problem(2) Garbage Collection (GC)

• GC is a process by which dynamically allocated storage is reclaimed during the execution of a program.

• Usually refers to automatic periodic storage reclamation by the garbage collector (part of the run-time system), as opposed to explicit code to free specific blocks of memory.

• Usually triggered during memory allocation when available free memory falls below a threshold. Normal execution is suspended and GC is run.

• Major GC algorithms:– Mark and sweep– Copying– Incremental garbage collection algorithms

Page 134: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

33

Mark and Sweep

• Oldest and simplest algorithm• Has two phases: mark and sweep• Collection algorithms: When program runs out of

memory, stop program, do garbage collection and resume program.

• Here: Keep free memory in free pool. When allocation encounters empty free pool, do garbage collection.

• Mark: Go through live memory and mark all live cells.

• Sweep: Go through whole memory and put a reference to all non-live cells into free pool.

Page 135: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

34

Mark Algorithm• Mark algorithm uses recursion as follows:

for every pointer r domark ( r )

end forprocedure mark ( ptr )

beginif ( ptr ≠ null ) then

if ptr^.tag is not marked thenset ptr^.tagmark ( ptr^.llink )mark ( ptr^.rlink )

end ifend if

Page 136: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

35

Problems with Garbage Collection (GC)

• The marking algorithm uses a great deal of storage (for stack space to use recursion).

• If your program need GC most (the program needs most of the cells in the heap), then the GC will work the worst (i.e. most of the cells must be traced and marked as being useful).

• The cost of additional space of the cell marks.• The extra execution time required to execute the

collection process.

Page 137: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Chapter 6Control Structures

Topics to cover here:

• Control Flow Within Expressions• Control Flow Among Program Statements

– Compound Statements– Selection Statements– Iterative Statements– Unconditional Branching

Page 138: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Control Structures • A control structure is a control statement and the

collection of statements whose execution it controls• Evolution:- FORTRAN I control statements were based directly

on IBM 704 hardware- Much research and argument in the1960s about the

issue- One important result: It was proven that all flowcharts

can be coded with only two-way selection and pretest logical loops

• Overall Design Question:- What control statements should a language have, beyond selection and pretest logical loops?

Page 139: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Levels of Control Flow

• There is control flow:1.Within expressions2.Among program statements3.Among program units

• Control Flow within Expressions- The expression is evaluated according to the

precedence rule imposed on the operators.- If the expression contains a function call as operand,

then the function call is evaluated first.

Page 140: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Control Flow Among Program Statements

• We want to see the control flow in the following statements:

- Compound Statements- Selection Statements- Iterative Statements- Unconditional Branching

Page 141: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Compound Statements

• A Compound statement- is in the form of one statement or more that are

enclosed by begin...end- it is abstracted as a single statement- it has advantage in control statements design- it is first introduced by ALGOL 60.

• A block is a compound statement that can define a new scope (with local variables).

Page 142: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Compound Statements .. Cont.

• Examples• Algol 60 has the block and compound statements

concepts.

• Pascal has compound statements but does not allow blocks.

• C, C++, and Java have compound statements and blocks that are delimited by braces (i.e. { and } ).

Page 143: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Selection Statements

• Design Issues:1. What is the form and type of the control

expression?2. What is the selectable segment form (single

statement, statement sequence, compound statement)?

3. How should the meaning of nested selectors be specified?

Page 144: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Selection Statements: Single-Way• Examples• FORTRAN IF: IF (boolean_expr)

statement

• Problems with this if:- It can select only a single statement; - To select more statements, a goto must be used, as in the

following exampleIF (FLAG .NE. 1) GOTO 20

I = 1J = 2

20 CONTINUE- Nesting of logical IF statements is not allowed.

Page 145: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Selection Statements: Single-Way.. Cont.

• ALGOL 60 if: if (boolean_expr) thenbegin

...end

• C++ if:if (boolean_expr)

{ statements; }

Page 146: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Selection Statements: Two-Way

• Examples• ALGOL 60 if:

if (boolean_expr) thenstatements

elsestatements

- The statements could be single or compound

Page 147: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Nesting Selectorse.g. (In Java or C++)

if (sum == 0 )if ( count == 0 )

result = 0 ;else

result = 1;

• The problem is: Which then gets the else? • The rule in Java or C++ is: the else goes with the nearest then.

• ALGOL 60's solution - disallow direct nesting, it uses compound statements

if sum = 0 then if sum = 0 thenbegin begin

if count = 0 then if count = 0 thenresult := 0 result := 0

else endresult := 1 else

end result := 1

Page 148: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Nesting Selectors .. Cont.

• FORTRAN 77, Ada, Modula-2 solution – closing with special words ( end if)

• In Ada:e.g.

if sum = 0 then if sum = 0 thenif count = 0 then if count = 0 then

result := 0 ; result := 0;else else

result := 1 ; end ifend if ; else

end if ; result := 1 ;end if;

Page 149: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

Nesting Selectors .. Cont.

• Advantage: flexibility and readability

• Modula-2 uses the same closing special word forall control structures (END).

This results in poor readability

Page 150: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

Multiple Selection Constructs

• Design Issues:

1. What is the form and type of the control expression?2. What segments are selectable (single, compound,

sequential)?3. Is the entire construct encapsulated?4. Is execution flow through the structure restricted to

include just a single selectable segment?5. What is done about unrepresented expression

values?

Page 151: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

Early Multiple Selectors1. FORTRAN arithmetic IF (a three-way selector)

IF (arithmetic expression) N1, N2, N3where, N1, N2, N3 are statement labels. The control goes to- N1 if the expression’s value is negative- N2 if the expression’s value is zero- N3 if the expression’s value is positive

• Bad aspects: - Not encapsulated (selectable segments could be anywhere)- Segments require GOTOs

2. FORTRAN computed GOTO and assigned GOTOGO TO (label1, label2, …, labeln), expression

According to the value of the expression (should be integer), a label is chosen

Page 152: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

Modern Multiple Selectors1. Pascal casecase expression of

constant_list_1 : statement_1;...constant_list_n : statement_n

end• Design choices:1. Expression is any ordinal type (int, boolean, char, enum)2. Segments can be single or compound3. Construct is encapsulated4. Only one segment can be executed per execution of the

construct5. In Wirth's Pascal, result of an unrepresented control expression

value is undefined (In 1984 ISO Standard, it is a runtime error)- Many dialects now have otherwise or else clause

Page 153: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

Modern Multiple Selectors .. Cont.2. The C and C++ switch

switch (expression){ constant_expression_1 : statement_1;

...constant_expression_n : statement_n;default: statement_n+1

}e.g.

switch (index){ case 1: case 3: odd += 1;

sumodd += index;case 2: case 4: even += 1;

sumeven += index;default: cout<<“Error in index “ ;

}

Page 154: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

18

Modern Multiple Selectors .. Cont.• Design Choices: (for switch)1. Control expression can be only an integer type2. Selectable segments can be statement sequences, blocks, or

compound statements3. Construct is encapsulated4. Any number of segments can be executed in one execution of

the construct (there is no implicit branch at the end ofselectable segments)

5. default clause is for unrepresented values (if there is no default, the whole statement does nothing)- Design choice 4 is a trade-off between reliability andflexibility (convenience)

- To avoid it, the programmer must supply a break statementfor each segment

Page 155: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

19

Modern Multiple Selectors .. Cont.

3. Ada's case is similar to Pascal's case, except:

1. Constant lists can include:- Subranges e.g., 10..15- Boolean OR operators, e.g., 1..5 | 7 | 15..20

2. Lists of constants must be exhaustive- Often accomplished with others clause- This makes it more reliable

Page 156: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

20

Modern Multiple Selectors .. Cont.• Multiple Selectors can appear as direct extensions to two-way

selectors, using else-if clauses. E.g. (ALGOL 68, FORTRAN 77, Modula-2, Ada)

In Ada:if ...

then ...elsif ...then ...

elsif ...then ...else ...

end if

- Far more readable than deeply nested if's- Allows a boolean gate on every selectable group

Page 157: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

21

Iterative Statements

The repeated execution of a statement or compound statement is accomplished either by iteration or recursion; here we look at iteration, because recursion is unit-level control

• General design Issues for iteration control statements:1. How is iteration controlled?2. Where is the control mechanism in the loop?

Page 158: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

22

Counter-Controlled Loops•Design Issues:

1. What is the type and scope of the loop var?2. What is the value of the loop var at loop

termination?3. Should it be legal for the loop var or loop

parameters to be changed in the loop body, and if so, does the change affect loop control?

4. Should the loop parameters be evaluated only once,or once for every iteration?

Page 159: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

23

Counter-Controlled Loops .. Cont.1. FORTRAN 77 and 90• Syntax:

DO label var = start, finish [, stepsize]- Stepsize can be any value but zero- Parameters can be expressions

• Design choices:1. Loop var can be INTEGER, REAL, or DOUBLE2. Loop var always has its last value3. The loop var cannot be changed in the loop, but

the parameters can; because they are evaluatedonly once, it does not affect loop control

4. Loop parameters are evaluated only once

Page 160: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

24

Counter-Controlled Loops .. Cont.2. ALGOL 60• Syntax:

for var := <list_of_stuff> do statementwhere <list_of_stuff> can have:- list of expressions- expression step expression until expression- expression while boolean_expression

Examples:1- for I := 1 step 1 until 10 do

list [I] := 02- for index := 1 step 2 until 50, 60, 70, 80, index + 1until 100 do

sum := sum + indexThis will have index = 1, 3, 5, 7, ..., 49, 60, 70, 80, 81, 82, ..., 100)

Page 161: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

25

Counter-Controlled Loops ..Cont.• ALGOL 60 Design choices:1. Control expression can be int or real; its scope is

whatever it is declared to be2. Control var has its last assigned value after loop

termination3. The loop var cannot be changed in the loop, but the

parameters can, and when they are, it affects loop control

4. Parameters are evaluated with every iteration, making it very complex and difficult to read

Page 162: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

26

Counter-Controlled Loops ..Cont.3. Pascal • Syntax:

for variable := initial (to | downto) final dostatement

• Design Choices:1. Loop var must be an ordinal type of usual scope2. After normal termination, loop var is undefined3. The loop var cannot be changed in the loop; the loop

parameters can be changed, but they are evaluated just once, so it does not affect loop control

Page 163: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

27

Counter-Controlled Loops ..Cont.4. C++Syntax:

for ( expression1 ; expression2; expression3){ statements}

- The first expression can include variable definition. (Scope is from the definition to the end of the loop body)

- It can use a boolean expression for loop control-The value of a multiple-statement expression is the value of the last

statement in the expression. e.g.,for (int I = 0; I< len; I++)

{ Statements }5. Java• Java’s for statement is like that of C++, except that the loop control

expression is restricted to boolean.

Page 164: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

28

Logically-Controlled Loops• Design Issues:1. Pretest or posttest?2. Should this be a special case of the counting loop statement (or a

separate statement)?

• Language Examples:1. Pascal has separate pretest and posttest logical loop statements

(while-do: the loop body is executed while condition is true; and repeat-until: the loop body is executed while condition is false )

2. C and C++ also have both, but the control expression for the posttest version is treated just like in the pretest case (while - do and do–while: the loop is executed while the condition is true).

3. Java is like C, except the control expression must be Boolean (and the body can only be entered at the beginning--Java has no goto)

4. Ada has a pretest version, but no posttest5. FORTRAN 77 and 90 have neither

Page 165: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

29

User-Located Loop Control MechanismsDesign issues:1. Should the conditional be part of the exit?2. Should the mechanism be allowed in an already controlled loop?3. Should control be transferable out of more than one loop?

Examples:1. Ada - conditional or unconditional; for any loop; any number of levels

for ... loop LOOP1:... while ... loopexit when ... ...... LOOP2:

end loop for ... loop...

exit LOOP1 when .....

end loop LOOP2;...

end loop LOOP1;

Page 166: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

30

User-Located Loop Control Mechanisms .. Cont.2. C , C++, and Java - break

Unconditional; for any loop or switch; one level only (Java’s can have a label). It causes to terminate the loop.There is also a continue statement for loops; it skips the remainder of this iteration, but does not exit the loop. E.g.

while (sum < 100) while (sum < 100) { cin >> value; { cin >> value;

if ( value < 0 ) continue; if ( value < 0 ) break;sum += value; sum += value;

} }

3. FORTRAN 90 - EXITUnconditional; for any loop, any number of levels

FORTRAN 90 also has CYCLE, which has the same semantics as C's continue

Page 167: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

31

Unconditional Branching

• An unconditional branch statement transfers execution control to a specified place in the program.

• Problem: readability- Some languages do not have them: e.g., Modula-2 , Java

• Label forms: 1. Unsigned int constants: Pascal (with colon) , FORTRAN (no

colon). For example,10: …

…if x < 0 goto 10

Page 168: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

32

Examples on Unconditional Branching2. Identifiers with colons: as in ALGOL 60, C. For example,

if ( x <10 ) thengo to L1

elsego to L2

3. Identifiers in << ... >>: Ada. E.g.goto FINISHED;…

<<FINISHED>> SUM := SUM + NEXT;4. Variables as labels: PL/I. E.g. Read c … goto c

- Labels can be assigned values and passed as parameters- Highly flexible, but make programs impossible to read anddifficult to implement

Page 169: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

33

Unconditional Branching .. Cont.Restrictions on Pascal's gotos:• A statement group is either a compound statement or the body

of a repeat-until

• The target of a goto cannot be a statement in a statement group that is not active- Means the target can never be in a statement group that is atthe same level or is nested more deeply than the one with thegoto

- An important remaining problem: the target can be in anyenclosing subprogram scope, as long as the statement is not

ina statement group

- This means that a goto can terminate any number ofsubprograms

Page 170: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Subprograms

Topics to cover:

• Fundamental Characteristics of Subprograms• Design Issues for Subprograms• Local referencing environments• Parameters and Parameter Passing• Generic Subprograms• Coroutines

Page 171: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Fundamental Characteristics of Subprograms

1. A subprogram has a single entry point

2. The caller is suspended during execution of the called subprogram

3. Control always returns to the caller when the called subprogram’s execution terminates

Basic definitions:• A subprogram definition is a description of the actions of the

subprogram abstractione.g. void adder (parameters)

• A subprogram call is an explicit request that the subprogram be executed

Page 172: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Fundamental Characteristics of Subprograms

• A subprogram header is the first line of the definition, including the name, the kind of subprogram, and the formal parameters

• The parameter profile of a subprogram is the number, order, and types of its parameters

• The protocol of a subprogram is its parameter profile plus, if it is a function, its return type

• A subprogram declaration provides the protocol, but not the body, of the subprogram

• A formal parameter is a dummy variable listed in the subprogram header and used in the subprogram

• An actual parameter represents a value or address used in the subprogram call statement

Page 173: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Actual/Formal Parameter Correspondence

1. Positional: The first actual parameter is bound to the first formal parameter and so forth. (This is done for short list of parameters).

2. Keyword: (it is used when list of parameters is long)

e.g. In Ada: SORT (LIST => A, LENGTH => N); where the definition of SORT procedure has the formal parameters LIST and LENGTH.

Advantage: order is irrelevantDisadvantage: user must know the formal parameter’s names

Page 174: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Actual/Formal Parameter Correspondence

• Default Values:e.g. procedure SORT(LIST : LIST_TYPE;

LENGTH : INTEGER := 100);...SORT (LIST => A);

where, LENGTH is default parameter.• The default parameter is usually placed as the last parameter.

• Procedures provide user-defined statements• Functions provide user-defined operators

Page 175: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Design Issues for Subprograms1. What parameter passing methods are provided?

2. Are parameter types checked?

3. Are local variables static or dynamic?

4. What is the referencing environment of a passed subprogram?

5. Are parameter types in passed subprograms checked?

6. Can subprogram definitions be nested?

7. Can subprograms be overloaded?

8. Are subprograms allowed to be generic?

9. Is separate or independent compilation supported?

Page 176: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Local referencing environments

• If local variables are stack-dynamic:- Advantages:

a. Support for recursionb. Storage for locals is shared among some subprograms

- Disadvantages:a. Allocation/deallocation timeb. Need for indirect addressing because of the stackc. Subprograms cannot be history sensitive (i.e. they cannot

retain data values of local variables between calls.

Page 177: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Local referencing environments

• Static locals are the opposite (e.g. a subprogram that generates pseudo random numbers, where each call to it computes one randomnumber using the last one it computed.

• In C++ functions, locals are stack dynamic unless specifically declared as static. E.g.int adder (int list[], int listlen){ static int sum = 0;

int count;for (count = 0; count < listlen; count++)

sum += list [count];return sum;

}• Pascal and Ada procedures and Java methods have only stack

dynamic local variables.

Page 178: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Parameters and Parameter Passing

• Semantic Models:1- in mode: Formal parameters receive data from the

corresponding actual parameters.2- out mode: Formal parameters can transmit data to the actual

parameters.3- inout mode: Formal parameters can do both

• Conceptual Models of Transfer:1. Physically move a value

2. Move an access path

Page 179: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Parameters and Parameter Passing .. Cont.

• Implementation Models:1. Pass-by-value (in mode)

- Either by physical move or access path- Disadvantages of access path method:

- Must write-protect in the called subprogram- Accesses cost more (indirect addressing)

- Disadvantages of physical move:- Requires more storage- Cost of the moves (if the parameter is large, such as a

long array)

Page 180: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Parameters and Parameter Passing .. Cont.2. Pass-by-result (out mode)

- Local’s value is passed back to the caller- Physical move is usually used

- Disadvantages:a. If value is passed, time and space b. In both cases, order dependence may be a problem

e.g.procedure sub1(y: int, z: int);...

sub1(x, x);value of x in the caller depends on order of assignments atthe return

Page 181: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Parameters and Parameter Passing .. Cont.3. Pass-by-value-result (inout mode)

- Physical move, both ways- Also called pass-by-copy- Disadvantages:

- Requires multiple storage for parameters- more time for copying values

4. Pass-by-reference (inout mode)- Pass an access path- Also called pass-by-sharing- Advantage: passing process is efficient in time and space.

Page 182: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

Parameters and Parameter Passing .. Cont.

- Disadvantages:a. Slower accesses (indirect addressing is needed) b. Can allow aliasing:

i. Actual parameter collisions:e.g. procedure sub1(a: int, b: int);

...sub1(x, x); // Here, a and b are aliases

ii. Array element collisions:e.g. sub1(a[i], a[j]);

// if i = j, a and b become aliases

Also, sub2(a, a[i]);

Page 183: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

Parameters and Parameter Passing .. Cont.

iii. Collision between formals and globals- Root cause of all of these is: The called subprogram is provided wider access to nonlocals than is necessary- Pass-by-value-result does not allow these aliases (but has other problems!)

5. Pass-by-name (multiple mode)- By textual substitution

- Formals are bound to an access method at the time of the call, but actual binding to a value or address takes place at the time of a reference orassignment

- Purpose: flexibility of late binding

Page 184: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

Parameters and Parameter Passing .. Cont.

- Resulting semantics:- If actual is a scalar variable, it is pass-by-reference- If actual is a constant expression, it is pass-by-value- If actual is an array element, it is like nothing else

e.g. procedure sub1(x: int; y: int);begin

x := 1;y := 2;x := 2;y := 3;

end;sub1(i, a[i]);

Page 185: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

Parameters and Parameter Passing .. Cont.If actual is an expression with a reference to a variable that is also accessible in the program, it is also like nothing else

e.g. (assume k is a global variable)procedure sub1(x: int; y: int; z: int);

begink := 1;y := x;

k := 5;z := x;

end;

sub1(k+1, j, i);- Disadvantages of pass by name:

- Very inefficient references- Too tricky; hard to read and understand

Page 186: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

Language Examples

1. FORTRAN- Before 77, pass-by-reference- 77 - scalar variables are often passed by value-result

2. ALGOL 60- Pass-by-name is default; pass-by-value is optional

3. ALGOL W- Pass-by-value-result

4. C- Pass-by-value

Page 187: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

18

Language Examples5. Pascal and Modula-2

- Default is pass-by-value; pass-by-reference is optional

6. C++- Like C, but also allows reference type parameters, which provide the

efficiency of pass-by-reference with in-mode semantics

7. Ada- All three semantic modes are available- If out, it cannot be referenced- If in, it cannot be assigned

8. Java- Like C++, except only references

Page 188: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

19

Type checking parameters- Now considered very important for reliability

- FORTRAN 77 and original C: none- Pascal, Modula-2, FORTRAN 90, Java, and Ada:

it is always required- ANSI C and C++: choice is made by the user

Page 189: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

20

Implementing Parameter Passing• ALGOL 60 and most of its descendants use the run-time stack

- By value: copy it to the stack; references are indirect to the stack- By result: same- By reference: regardless of form, put the address in the stack- By name: run-time resident code segments or subprograms evaluate the

address of the parameter; called for each reference to the formal; these arecalled thunks

- Very expensive, compared to reference or value-result

• Ada- Simple variables are passed by copy (value-result)- Structured types can be either by copy or reference

- This can be a problem, because a) Of aliases (reference allows aliases, but value-result does not)b) Procedure termination by error can produce different actual parameter

results- Programs with such errors are “erroneous”

Page 190: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

21

Multidimensional Arrays as Parameters• If a multidimensional array is passed to a subprogram and the

subprogram is separately compiled, the compiler needs to know the declared size of that array to build the storage mapping function

• C and C++- Programmer is required to include the declared sizes of all but the

first subscript in the actual parametere.g. void fun (int matrix [ ] [10] )

{ … }void main ( ){ int mat [5][10];

…fun (mat) ;… }

Page 191: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

22

Multidimensional Arrays as Parameters- This disallows writing flexible subprograms- Solution: pass a pointer to the array and the sizes of the

dimensions as other parameters; the user must include the storage mapping function, which is in terms of the size of parameters.e.g. void fun (float *matPtr, int nrows, int, ncol)

• Pascal- Not a problem (declared size is part of the array’s type)

• Ada- Constrained arrays - like Pascal- Unconstrained arrays - declared size is part of the object declaration (See book example p. 351)

Page 192: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

23

Generic Subprograms• A generic or polymorphic subprogram is one that takes

parameters of different types on different activations

• Overloaded subprograms provide ad hoc polymorphism• A subprogram that takes a generic parameter that is used in a

type expression that describes the type of the parameters of thesubprogram provides parametric polymorphism

• Examples of parametric polymorphism1. Ada

- Types, subscript ranges, constant values, etc., can be genericin Ada subprograms and packages

Page 193: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

24

Generic Subprogramsgenerictype ELEMENT is private;type VECTOR is array (INTEGER range <>) of ELEMENT;procedure GENERIC_SORT(LIST: in out VECTOR);procedure GENERIC_SORT(LIST: in out VECTOR)

isTEMP : ELEMENT;beginfor INDEX_1 in LIST'FIRST ..

INDEX_1'PRED(LIST'LAST) loopfor INDEX_2 in INDEX'SUCC(INDEX_1) ..

LIST'LAST loopif LIST(INDEX_1) > LIST(INDEX_2) then

TEMP := LIST (INDEX_1);LIST(INDEX_1) := LIST(INDEX_2);LIST(INDEX_2) := TEMP;

end if;end loop; -- for INDEX_1 ...

end loop; -- for INDEX_2 ...end GENERIC_SORT;

procedure INTEGER_SORT is new GENERIC_SORT(ELEMENT => INTEGER;VECTOR => INT_ARRAY);

Page 194: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

25

Generic Subprograms2. C++- Templated functions- e.g.template <class Type>Type max (Type first, Type second) { return first > second ? first : second ;}

• C++ template functions are instantiated implicitly when the function is named in a call or when its address is taken with the & operator

Page 195: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

26

Generic SubprogramsAnother example:

template <class Type>void generic_sort(Type list[], int len) {int top, bottom;Type temp;for (top = 0; top < len - 2; top++)for (bottom = top + 1; bottom < len - 1; bottom++) { if (list[top] > list[bottom])

{ temp = list [top];list[top] = list[bottom];list[bottom] = temp;

}} //** end of for (bottom = ...

} //** end of generic_sort

Page 196: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

27

Generic Subprograms• Example use:

float flt_list[100]; ...generic_sort(flt_list, 100); // Implicit instantiation

Definition: Independent compilation is compilation of some of the units of a program separately from the rest of the program, without the benefit of

interface information

Definition: Separate compilation is compilation of some of the units of a program separately from the rest of the program, using interfaceinformation to check the correctness of the interface between the two parts.

• Language Examples:- FORTRAN II to FORTRAN 77 - independent- FORTRAN 90, Ada, Modula-2, C++ - separate- Pascal - allows neither

Page 197: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

28

Accessing Nonlocal EnvironmentsDef: The nonlocal variables of a subprogram are those that are visible but not

declared in the subprogram

• Def: Global variables are those that may be visible in all of the subprograms of a program

1. Static scoping - discussed in previous lectures2. External declarations - C

- Subprograms are not nested- Globals are created by external declarations (they are simply defined outside any function)- Access is by either implicit or explicit declaration- Declarations (not definitions) give types to externally defined variables (and say they are defined elsewhere)

3. External modules - Ada and Modula-24. Dynamic Scope - discussed previously

Page 198: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

29

Coroutines

• A coroutine is a subprogram that has multiple entries and controls them itself.- Also called symmetric control- A coroutine call is named a resume- The first resume of a coroutine is to its beginning, but

subsequent calls enter at the point just after the last executedstatement in the coroutine

- Typically, coroutines repeatedly resume each other, possiblyforever

- Coroutines provide quasiconcurrent execution of programunits (the coroutines)

- Their execution is interleaved, but not overlapped

Page 199: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 1

Subprogram Implementations• The subprogram call and return operations of a language are together

called its subprogram linkage

• Implementing FORTRAN 77 SubprogramsCall Semantics:1. Save the execution status of the caller2. Carry out the parameter-passing process3. Pass the return address4. Transfer control to the callee

Return Semantics:1. If pass-by-value-result parameters are used, move the current values of

those parameters to their corresponding actual parameters2. If it is a function, move the functional value to a place the caller can get it3. Restore the execution status of the caller4. Transfer control back to the caller

Required Storage:- Status information of the caller, parameters, return address, and functional

value (if it is a function)

Page 200: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 2

Activation Records

• Activation Record is the format, or layout, of the noncode part of an executing subprogram.

• An activation record instance is a concrete example of an activation record (the collection of data for a particular subprogram activation)

• FORTRAN 77 subprograms can have no more than one activation record instance at any given time

• The code of all of the program units of a FORTRAN 77 program may reside together in memory, with the data for all units stored together elsewhere

• The alternative is to store all local subprogram data with the subprogram code

Page 201: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 3

Implementing Subprograms in ALGOL-like Languages

• This is more complicated than implementing FORTRAN 77 subprograms because:

- Parameters are often passed by two methods- Local variables are often dynamically allocated- Recursion must be supported- Static scoping must be supported

- A typical activation record for an ALGOL-like language:

Local variablesParametersDynamic linkStatic link stack topReturn address

Page 202: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 4

Implementing Subprograms in ALGOL-like Languages .. Cont.

• The activation record format is static, but its size may be dynamic

• An activation record instance is dynamically created when a subprogram is called

• The static link points to the bottom of the activation record instance of an activation of the static parent (used for access to nonlocal variables)

• The dynamic link points to the top of an instance of the activation record of the caller

Page 203: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 5

Implementing Subprograms in ALGOL-like Languages: An Example

program MAIN_1;var P : real;procedure A (X : integer);var Y : boolean;procedure C(Q : boolean);begin { C }... <------------------------3end; { C }

begin { A }... <--------------------------2C(Y);...end; { A }procedure B(R : real);var S, T : integer;begin { B }... <------------------------1A(S);...end; { B }

begin { MAIN_1 }B(P);

end. { MAIN_1 }

Note that: MAIN_1 calls B, B calls A, A calls C

Page 204: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 6

Implementing Subprograms in ALGOL-like Languages

• The collection of dynamic links in the stack at a given time is called the dynamic chain, or call chain

• Local variables can be accessed by their offset from the beginning of the activation record. This offset is called the local_offset

• The local_offset of a local variable can be determined by the compiler• Assuming all stack positions are the same size, the first local variable declared

has an offset of three plus the number of parameters

e.g. In MAIN_1, the local_offset of Y in A is 4

• The activation record used in the previous example supports recursion

e.g. int factorial(int n) {<-----------------------------1

if (n <= 1)return 1;

else return (n * factorial(n - 1));<-----------------------------2

}void main() {int value;value = factorial(3);<-----------------------------3

}

Page 205: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 7

Nonlocal References - Static Scoping

• Observation: All variables that can be nonlocally accessed reside in some activation record instance in the stack

• The process of locating a nonlocal reference:

1. Find the correct activation record instance2. Determine the correct offset within that activation record instance

• Finding the offset is easy!

• Finding the correct activation record instance:Static semantic rules guarantee that all nonlocal variables that can be referenced have been allocated in some activation record instance that is on the stack when the reference is made

Page 206: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 8

Technique 1 - Static Chains• A static chain is a chain of static links that connects certain activation

record instances

• The static link in an activation record instance for subprogram A points to one of the activation record instances of A's static parent

• The static chain from an activation record instance connects it to all of its static ancestors

To find the declaration for a reference to a nonlocal variable:

• You could chase the static chain until the activation record instance (ari) that has the variable is found, searching each ari as it is found

• Definition: Static_depth is an integer associated with a static scope whose value is the depth of nesting of that scope

Page 207: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 9

Technique 1 - Static Chains .. Cont.e.g. main ----- static_depth = 0

A ----- static_depth = 1B ----- static_depth = 2

C ----- static_depth = 1

• Definition: The chain_offset or nesting_depth of a nonlocal reference is the difference between the static_depth of the reference and that of the scope where it is declared

A reference can be represented by the pair:

(chain_offset, local_offset)

9where local_offset is the offset in the activation record of the variable being referenced

Page 208: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 10

Static Chains: Example Programprogram MAIN_2;

var X : integer;procedure BIGSUB;

var A, B, C : integer;procedure SUB1;var A, D : integer;begin { SUB1 }A := B + C; <-----------------------1end; { SUB1 }

procedure SUB2(X : integer);var B, E : integer;procedure SUB3;var C, E : integer;begin { SUB3 }SUB1;E := B + A: <--------------------2end; { SUB3 }

begin { SUB2 }SUB3;A := D + E; <-----------------------3end; { SUB2 }

begin { BIGSUB }SUB2(7);end; { BIGSUB }

beginBIGSUB;end. { MAIN_2 }

Page 209: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 11

Static Chains: Example Program

Call sequence for MAIN_2MAIN_2 calls BIGSUB, BIGSUB calls SUB2,SUB2 calls SUB3, SUB3 calls SUB1

At position 1 in SUB1:A - (0, 3)B - (1, 4)C - (1, 5)

At position 2 in SUB3:E - (0, 4)B - (1, 4)A - (2, 3)

At position 3 in SUB2:A - (1, 3)D - an error

Page 210: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 12

Static Chain MaintenanceAt the call (assume there are no parameters that are subprograms and no pass-by-name parameters):

- The activation record instance must be built- The dynamic link is just the old stack top pointer- The static link must point to the most recent ari of the static parent (in most

situations)Two Methods:

1. Search the dynamic chain until the first ari for the static parent is found--easy,but slow

2. Treat procedure calls and definitions like variable references and definitions(have the compiler compute the nesting depth, or number of enclosing scopesbetween the caller and the procedure that declared the called procedure; storethis nesting depth and send it with the call)

e.g. Look at MAIN_2 and Figure 9.9At the call to SUB1 in SUB3, this nesting depth is 2, which is sent to SUB1 with the call. The static link in the new ari for SUB1 is set to point to the ari that is pointed to by the second static link in the static chain from the ari for SUB3

Page 211: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 13

Evaluation of the Static Chain Method

Problems:

1. A nonlocal reference is slow if the number ofscopes between the reference and the declarationof the referenced variable is large

2. Time-critical code is difficult, because the costsof nonlocal references are not equal, and can change with code upgrades

Page 212: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 14

Technique 2 - Displays

The idea: Put the static links in a separate stack called a display. The entries in the display are pointers to the ari'sthat have the variables in the referencing environment.

Represent references as

(display_offset, local_offset)

where display_offset is the same as chain_offset14

Page 213: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 15

Mechanics of References

- Use the display_offset to get the pointer into the display to the ari with the variable

- Use the local_offset to get to the variable within the ari

Display maintenance (assuming no parameters that are subprograms and no pass-by-name parameters)

- Note that display_offset depends only on the static depth of the procedure whose ari is being built. It is exactly the static_depth of the procedure.

- There are k+1 entries in the display, where k is the static depth of the currently executing unit (k=0 is for the main program)

- For a call to procedure P with a static_depth of k: a. Save, in the new ari, a copy of the display pointer at position kb. Put the link to the ari for P at position k in the display

- At an exit, move the saved display pointer from the ari back into the display atposition k

Page 214: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 16

Mechanics of ReferencesTo see that this works:

- Let Psd be the static_depth of P, and Qsd be the static_depth of Q- Assume Q calls P

- There are three possible cases:1. Qsd = Psd2. Qsd < Psd3. Qsd > Psd

Example skeletal program:program MAIN_3;procedure BIGSUB;

procedure SUB1;end; { SUB1 }

procedure SUB2;procedure SUB3;end; { SUB3 }

end; { SUB2 }end; { BIGSUB }

end. { MAIN_3 }

MAIN_3 can illustrate all three cases

Page 215: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 17

Case 1: SUB2 calls SUB1

Before the call, we have:

ARI for SUB2 2ARI for BIGSUB 1ARI for MAIN_3 0

Stack Display

After the call, we have:

ARI for SUB1 2ARI for SUB2

1ARI for BIGSUB

0ARI for MAIN_3

Stack Display

Page 216: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 18

Comparing the Static Chain and Display Methods

1. References to locals- Not much difference

2. References to nonlocals- If it is one level away, they are equal- If it is farther away, the display is faster- Display is better for time-critical code, because all nonlocal

references cost the same3. Procedure calls

- For one or two levels of depth, static chain is faster- Otherwise, the display is faster

4. Procedure returns- Both have fixed time, but the static chain is slightly faster

Overall: Static chain is better, unless the display can be kept in registers(The display can be kept in registers, if there are enough--it speeds up

access and maintenance)

Page 217: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 19

Implementing Blocks

Two Methods:1. Treat blocks as parameterless subprograms

- Use activation records2. Allocate locals on top of the ari of the subprogram

- Must use a different method to access locals- A little more work for the compiler writer

Implementing Dynamic Scoping1. Deep Access - nonlocal references are found by searching the activation

record instances on the dynamic chain- Length of chain cannot be statically determined- Every activation record instance must have variable names

2. Shallow Access - put locals in a central placeMethods:

a. One stack for each variable name (see p. 403)b. Central table with an entry for each variable

Page 218: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 20

Implementing Parameters that are Subprogram Names (deep binding)

1. Static chain- Compiler simply passes the link to the static

parent of the parameter, along with the parameter

2. Display- All pointers to static ancestors must be saved,

because none are necessarily in the environment of the parameter

- In many implementations, the whole display issaved for calls that pass subprogram parameters

Page 219: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 21

Implementing Parameters that are Subprogram Names (deep binding)

Another look at the referencing environment for a passed subprogram.Consider the following skeletal program:program MAIN_7;

procedure SUB1;begin { SUB1 }

...end; { SUB1 }

procedure SUB2(procedure SUBX);var SUM : real;procedure SUB3;begin { SUB3 }SUM := 0.0;

...end; { SUB3 }

begin { SUB2 }SUBX;SUB2(SUB3);...end; { SUB2 }

begin { MAIN_7 }...SUB2(SUB1);...end. { MAIN_7 }

Which activation of SUB2 has the SUM that SUB3 assigns?

Page 220: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages 22

Execution of MAIN_7 Program

• MAIN_7 calls SUB2, sending SUB1 as a parameter.• SUB2 then calls the passed procedure SUB1• Upon return from SUB1, SUB2 calls itself, sending its

own procedure, SUB3, as a parameter.• There are now two instances of the activation record for

SUB2 on the stack, the topmost being for the recursive call.

• The topmost activation of SUB2 then calls SUB3.• When SUB3 uses the variable SUM, there are two

activations of it, one for each activation of SUB2 where it is declared.

• Because the referencing environment of SUB3 is that of the caller that sent SUB3 as parameter, it is the first activation of SUB2, not the most recent.

Page 221: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

Functional Programming Languages

Topics to cover:• Mathematical Functions• Fundamentals of Functional Programming

Languages • LISP• Applications of Functional Languages• A Comparison of Functional and Imperative

Languages

Page 222: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

Functional Programming Languages: Introduction

• Imperative languages depend on Von Neumann architecture.

• The imperative style of programming relies heavily on the underlying architecture, which is considered to be unnecessary restriction on the process of software development.

• The functional programming paradigm, which is based on mathematical functions, is the design basis for one of the most important non-imperative styles of languages.

• This style is supported by functional, or applicative, programming languages.

• LISP began as a purely functional language but soon acquired some important imperative features that increased its execution efficiency.

Page 223: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Mathematical Functions

• A mathematical function is a mapping of members of one set, called the domain set, to another set, called the range set.

• The domain set, the range set, and the mapping have to be specified in the definition of the function.

• The mapping is described by an expression, or by a table.

• Functions are often applied to a particular element of the domain set.

• A function yields or returns an element of the range set.

Page 224: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Characteristics of Mathematical Functions

• The evaluation order of their mapping expressions is controlled by recursion and conditional expressions, rather than by sequencing and iterative repetition that are common to the imperative programming languages.

• Because they have no side effects, they always define the same value given the same set of arguments.

• Side effects in PLs are connected to variables that model memory locations. A mathematical function defines a value, rather than specifying a sequence of operations on values in memory to produce a value.

• There are no variables in the sense of imperative language, so there can be no side effects.

Page 225: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Simple Functions

• Function definition is written as- a function name- followed by a list of parameters in parentheses- followed by the mapping expression

For example:cube (x) ≡ x * x * x, where x is a real number

• In this example, the domain and range sets are the real numbers.• The symbol ≡ is used to mean “is defined as”.• The parameter x can represent any number of the domain set, but it

is fixed to represent one specific element during evaluation of the function expression.

Page 226: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Simple Functions .. Cont.

• This is how the parameters of mathematical functions differ fromthe variables in imperative languages.

• Function application is specified by pairing the function name with a particular element of the domain set.

• The range element is obtained by evaluating the function mappingexpression with the domain element substituted for the occurrence of the parameter.

• For example, cube (2.0) yields the value 8.0• During evaluation, the mapping of a function contains no unbound

parameters, where a bound parameter is a name for a particular value.

Page 227: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Lambda Notation• Functions can be defined using Lambda notation.• Lambda notation provides a method for defining nameless functions.• A Lambda expression specifies the parameter and the mapping of a

function.• The lambda expression is the function itself.• For example, consider the previous cube function written as lambda

expression:λ (x) x * x * x

• When lambda expression is evaluated for a given parameter, the expression is said to be applied to that parameter.

• The application of the lambda expression above is denoted as in the following example:

(λ (x) x * x * x) (2)Which results in the value 8.

Page 228: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Function Forms• A higher-order function, or functional form, is one that either takes

functions parameters or yields function as it result, or both.• One kind of functional form is function composition., which has

two functional parameters and yields function whose value is the first actual parameter function applied to the result of the second.

• Function composition is written as an expression, using ° as an operator, as in

h ≡ f ° g

• For example, iff(x) ≡ x + 2g(x) ≡ 3 * x

then h is defined ash(x) ≡ f ( g(x) ), or h(x) ≡ (3 * x ) + 2

Page 229: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Function Forms .. Cont.• Construction is a functional form that takes a list of functions

as parameters.• When applied to an argument, construction applies each of its

functional parameters to that argument and collects the results in a list or sequence.

• A construction is denoted by placing the functions in bracket asin [f, g].

• Example:Let g(x) ≡ x * x

h(x) ≡ 2 * xi(x) ≡ x / 2

then[ g, h, i ] (4) yields ( 16, 8, 2 )

Page 230: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Function Forms .. Cont.• Apply-to-all is a function form that takes a single

function as a parameter.• If applied to a list of arguments, apply-to-all applies its

functional parameter to each of the values in the list argument and collects the results in a list or sequence.

• Apply-to-all is denoted by α.• Example:

Leth(x) ≡ x * x

thenα (h, (2, 3, 4)) yields ( 4, 9, 16 )

Page 231: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Fundamentals of Functional Programming Languages

• The objective of the design of functional programming (FP) language is to mimic mathematical function to the greatest extent possible.

• The design of functional programming languages results in an approach to problem solving that is different from methods used with imperative languages.

• In an imperative language, an expression is evaluated and the result is stored in a memory location, which is represented as avariable in a program.

• A purely functional programming language does not use variables or assignment statements.

Page 232: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Fundamentals of Functional Programming Languages

• In FP- The programmer does not concern about the memory cells of

the computer on which the program is executed.- Without variables, iterative constructs are not possible.- Repetition must be done by recursion. - Programs are function definitions and function application

specifications- Executions consist of evaluating the function application.

• Without variables, the execution of a purely functional program has no state in the sense of operational and denotational semantics.

• The execution of a function always produces the same result whengiven the same parameters. This is called referential transparency.

Page 233: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

Fundamentals of Functional Programming Languages

• A functional language provides- a set of primitive functions- a set of functional forms to construct complex functions fromthose primitive functions

- a function application operation- some structures to represent data. These structures are used to

represent the parameters and values computed by functions.

• Functional languages are often implemented with interpreters.

Page 234: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

The First Functional Programming Language: LISP

• LISP (developed by McCarthy) stands for List Processing.• Data Types and Structures in LISP are atoms and lists

- Atoms, which have the form of identifiers, are the symbols ofLISP. Numeric constants are also atoms.

- Lists are specified by delimiting their element within parentheses.- The elements of simple lists are restricted to atoms, as in

( A B C D )- Nested list structures are also specified by parentheses.

E.g. the list (A ( B C ) D ( E ( F G ) ) ) is a list of 4 elements:The first element is the atom A; The second is the sublist ( B C );The third is the atom D; The fourth is the sublist (E ( F G ) ),which has as its second element the sublist ( F G )

Page 235: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

LISP .. Cont.

• Internally, lists are stored as single-linked list structures, in which each node has two pointers and represents an element.

• A node for an atom has its first pointer pointing to some representation of the atom, such as its symbol or numeric value.

• A node for a sublist element has its first pointer pointing to the first node of the sublist.

• In both cases, the second pointer of a node points to the next element of the list.

• A list is referenced by a pointer to its first element.

Page 236: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

16

LISP .. Cont.

• Example: The list ( A ( B C ) D ) ) is represented as follows

A D

B C

Page 237: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

17

Functions in LISP• Function calls are also expressed in list notation.• Function calls are specified in a prefix list form such as:

( function_name argument_1 … argument_n )

• For example, if + is function that takes two numeric parameters, then ( + 5 7 ) evaluates to 12.

• The lambda notation is chosen to specify function definitions.• It is modified to allow the binding of functions to names so that functions

could be referenced by other functions and by themselves.• This name binding was specified by a list consisting of the function name

and a list containing the lambda expression as in(function_name (LAMBDA (arg_1 … arg_n) expression )

• LISP functions specified as in the above notation were called S-expressions, for symbolic expressions.

Page 238: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

1

An Introduction to Scheme

• The Scheme language, which is a dialect of LISP, emerged from MIT in the mid-1970s.

• Main characteristics of Scheme:- It is of small size, then it can be suitable for educational

applications- It uses static scoping exclusively- It treats functions as first-class entities:

-- Its functions can be the values of expressionsand elements of lists

-- they can be assigned to variables and passed asparameters

Page 239: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

2

An Introduction to Scheme .. Cont.

• Names in Scheme can consist of letters, digits, and special characters except parentheses;

• Names are case insensitive but must not begin with a digit.

• The Scheme interpreter is a read-evaluate-write infinite loop. It repeatedly reads an expression typed by the user, interprets the expression, and display

Page 240: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

3

Primitive Functions in Scheme• Scheme has +, -, *, / as primitive functions.• + adds all of its parameters (it could take 0 parameters, then it returns 0)• * multiplies all of its parameters (it could take 0 parameters, then it returns

1)• - and / can have 2 or more parameters• SQRT is a function to return the square root of its numeric parameter.

ExamplesExpression value42 42(* 3 7 ) 21(+ 5 7 8 ) 20(- 5 6 ) -1(-15 7 2 ) 6(-24 ( * 4 3 ) ) -12

Page 241: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

4

Primitive Functions in Scheme

• EVAL is the basis of all function evaluation in Scheme. It is called to handle the evaluate part of the read-evaluate-write action of Scheme interpreter.

• When applied to a primitive function, EVAL first evaluates the parameters of the given function, when the actual parameters are function calls.

• If the parameters are data elements, either atoms or lists, thenthey should not be evaluated

• For example, suppose we have a function with two parameters, an atom and a list, whose purpose is to determine whether the give atom is in the list, ten no need to evaluate the atom or the list just to be examined.

• To avoid evaluating a parameter, first it is given as a parameter to the primitive function QUOTE

Page 242: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

5

Primitive Functions in Scheme

• Example(QUOTE A) returns A(QUOTE ( A B C )) returns ( A B C )

• QUOTE can be abbreviated by the symbol (‘). Thus (QUOTE (A B)) can be written as ‘ (A B )

• There are two primitive list selectors in Scheme: - CAR to return the first element of a given list- CDR to return the remainder of a given list after its CAR isremoved.

- CONS is the list constructor. It builds a list from its 2 arguments, the firstis tom or list and the second is usually a list.

Page 243: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

6

Primitive Functions in Scheme

• Examples(CAR ‘ ( A B C ) ) returns A(CAR ‘ ( ( A B ) C D ) ) returns ( A B )(CAR ‘ A ) is an error because A is not a list(CAR ‘ (A)) returns A(CAR ‘( ) ) is an error, ( ) is an empty list

(CDR ‘(A B C )) returns ( B C )(CDR ‘ ( ( A B ) C D ) ) returns ( C D )(CDR ‘A ) is an error(CDR ‘(A)) returns ( )

Page 244: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

7

Primitive Functions in Scheme

(CONS ‘ A ( ) ) returns (A)(CONS ‘A ‘( B C ) ) returns ( A B C )(CONS ‘( ) ‘ ( A B ) ) returns ( ( ) A B )(CONS ‘( A B ) ‘ (C D ) ) returns ( ( A B ) C D )

• LIST is a function that constructs lists from a variable number of parameters. E.g.

( LIST ‘apple ‘orange ‘grape )

Page 245: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

8

Functions for Constructing Functions• LISP-based languages use lambda notation in list form to define functions,

e.g.( LAMBDA ( L ) ( CAR ( CDR L ) ) ) ‘( A B C )which yields B.

• Here L is called bound variable within lambda expression.• DEFINE is function that serves the following:

1- to bind a name to a value. 2- to bind a name to a lambda expression

• For case (1), this is to create named constants, e.g.(DEFINE pi 3.14159 )

• For case (2), the lambda expression is abbreviated to remove the word lambda. DEFINE takes two lists as parameters:- the first is the prototype of a function call with the function name followed by the formal parameters, all in a list- the second list is the expression to which the name is to be bound.

Page 246: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

9

Functions for Constructing Functions• The general for of DEFINE is

( DEFINE ( function_name parameters )body

)EX1:

(DEFINE (square number ) ( * number number ) )This can be used as in (square 5 ) which displays 25

EX2(DEFINE ( hypotenuse side1 side2 )

(SQRT ( + (square side1 ) ( square side2))))This uses function square defined before.

Page 247: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

10

Predicate Functions• In Scheme, there are three important primitive functions:

- EQ? To test the two symbolic parameters for equality- NULL? To test if list is null- LIST? To test if the argument is list

These functions return #T for true or #F (or empty list ( ) ) for false.e.g.(EQ? ‘A ‘A ) returns #T(EQ? ‘A ‘B ) returns ( )(EQ? ‘A ‘( A B)) returns ( )(LIST? ‘(X Y)) returns #T(LIST? ‘X) returns ( )(NULL ‘( ) ) returns #T(NULL? ‘A) returns ( )

Page 248: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

11

Control Flow

Mathematical functions use recursione.g.

1 if n = 0f(n) =

n * f (n-1) if n > 0

Scheme has two control structures:

1- IF structure for two way selectionSyntax:

(IF predicate then_expression else_expression)

Page 249: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

12

Control Flow .. Cont.

2- COND structure for multi way selection

Syntax:

(COND(predicate_1 expression {expression} )(predicate_2 expresion {expresion} )…(predicate_n expression {expresion} )(ELSE expresion {expresion} )

)

Page 250: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

13

Control Flow ExamplesExample 1:Function f above can be written as using IF structure:(DEFINE (factorial n)

( IF ( = n 0 )1( * n ( factorial ( - n 1 ) ) )

) )

Example 2:(DEFINE ( compare x y )

( COND( ( > x y ) ( DISPLAY “x is greater than y” ) )( ( < x y ) ( DISPLAY “x is less than y” ) ) ( ELSE ( DISPLAY “ x and y are equal “ ) )

)

Page 251: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

14

Control Flow Examples .. Cont.Example 3:Consider the problem of determining whether two lists are equal.

(DEFINE ( equalsimp list1 list2 )( COND

( ( NULL? list1 ) ( NULL? list2 ) )( ( NULL? list2 ) ‘( ) )( ( EQ? ( CAR list1 ) ( CAR list2 ) )

( equalsimp ( CDR list1 ) ( CDR list2 ) ) )( ELSE ‘ ( ) )

) )

Page 252: Concepts of Programming Languages (750321) Files/cs/750321le.pdf · Concepts of Programming Languages (750321) ... (e.g. Lisp, ML) Rule-based (e.g. Prolog) ... • The program reader

Concepts of Programming Languages

15

Control Flow Examples .. Cont.Example 4:Consider the following function (guess) that yields a simple list that contains the common elements of its two parameter lists.

(DEFINE ( guess list1 list2 ) ( COND

( ( NULL? list1 ) ‘ ( ) )( ( member ( CAR list1 ) list2 )

( CONS ( CAR list1) (guess (CDR list1 ) litst2 ) ) )( ELSE ( guess (CDR list1 ) list2 ) )

) )(DEFINE ( member atm list1 )

(COND( ( NULL? List1 ‘ ( ) )( ( EQ? atm ( CAR list1 ) ) #T )( ELSE ( member atm ( CDR list1 ) ) )

) )