0% found this document useful (0 votes)
292 views375 pages

Principles of Programming Languages: Dr. N. Papanna

This document provides an overview of principles of programming languages. It discusses reasons for studying programming language concepts, including improved ability to express ideas, choose appropriate languages, and better understand language implementation. It also covers programming domains, language evaluation criteria, influences on language design like computer architecture and programming methodologies, categories of languages, design trade-offs, and implementation methods. The overall document serves as an introductory guide to key concepts in programming languages.

Uploaded by

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

Principles of Programming Languages: Dr. N. Papanna

This document provides an overview of principles of programming languages. It discusses reasons for studying programming language concepts, including improved ability to express ideas, choose appropriate languages, and better understand language implementation. It also covers programming domains, language evaluation criteria, influences on language design like computer architecture and programming methodologies, categories of languages, design trade-offs, and implementation methods. The overall document serves as an introductory guide to key concepts in programming languages.

Uploaded by

Tharaka Roopesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

PRINCIPLES OF

PROGRAMMING LANGUAGES
Prepared By:
Dr. N. PAPANNA
Asst Professor
Department of CSE, SVEC

1
2
CONCEPT
❖ Reasons for StudyingSConcepts of Programming
Languages.
❖ Programming Domains
❖ Language Evaluation Criteria
❖ Influences on Language Design
❖ Language Categories
❖ Language Design Trade-Offs
❖ Implementation Methods
❖ Programming Environments

Unit-1(PRINCIPLES OF
1-3
PROGRAMMING LANGUAGES)
❖ Reasons for Studying Concepts of
Programming Languages
● Increased ability to express ideas.
● Improved background for choosing appropriate
languages.
● Increased ability to learn new languages.
● Better understanding of significance of implementation.
● Better use of languages that are already known.
● Overall advancement of computing.

Unit-1(PRINCIPLES OF
1-4
PROGRAMMING LANGUAGES)
❖Programming Domains
• Scientific Applications
– Large numbers of floating point computations; use of
arrays.
– Example:Fortran.
• Business Applications
– Produce reports, use decimal numbers and
characters.
– Example:COBOL.
• Artificial intelligence
– Symbols rather than numbers manipulated; use of linked
lists.
– Example:LISP.

Unit-1(PRINCIPLES OF
PROGRAMMING LANGUAGES)
1-6
❖Programming Domains
● System programming
- Need effieciency because of continous use.
- Example:C

● Web Software
-Eclectic collection of languages:
markup(example:XHTML),scripting(example:PHP),
general-purpose(example:JAVA).

7
❖Language Evaluation Criteria
● Readability:
➢ The ease with which programs can be read and
understood.
● Writability:
➢ The ease with which a language can be used to create
programs.
● Reliability:
➢ Conformance to specifications (i.e., performs to its
specifications).
● Cost:
➢ The ultimate total [Link]-1(PRINCIPLES OF
1-8
PROGRAMMING LANGUAGES)
❖Evaluation Criteria: Readability
➔ Overall simplicity
◆ A manageable set of features and constructs.
◆ Minimal feature multiplicity .
◆ Minimal operator overloading.
➔ Orthogonality
◆ A relatively small set of primitive constructs can be
combined in a relatively small number of ways
◆ Every possible combination is legal
➔ Data types
◆ Adequate predefined data types.

Unit-1(PRINCIPLES OF
PROGRAMMING LANGUAGES)
❖Evaluation Criteria:Readability

➔ Syntax considerations
-Identifier forms:flexible composition.
-Special words and methods of forming
compound statements.
-Form and meaning:self-descriptive
constructs,meaningful keywords.

10
❖Evaluation Criteria: Writability
• Simplicity and orthogonality
– Few constructs, a small number of primitives, a small
set of rules for combining them.
● Support for abstraction
-The ability to define and use complex structures
or operations in ways that allow details to be ignored.
● Expressivity
– A set of relatively convenient ways of specifying
operations.
– Strength and number of operators and
predefined
functions.
Unit-1(PRINCIPLES OF
1-10
PROGRAMMING LANGUAGES)
❖Evaluation Criteria: Reliability

• Type checking
– Testing for type errors.
• Exception handling
– Intercept run-time errors and take corrective measures.
• Aliasing
– Presence of two or more distinct referencing methods for
the same memory location.
• Readability and writability
– A language that does not support “natural” ways of
expressing an algorithm will require the use
of
“unnatural” approaches, and hence
Unit-1(PRINCIPLES OF reduced 1-11
PROGRAMMING LANGUAGES)
❖Evaluation Criteria: Cost
• Training programmers to use the language
• Writing programs (closeness to particular
applications)
• Compiling programs
• Executing programs
• Language implementation system:
availability of free compilers
• Reliability: poor reliability leads to
high costs
• Maintaining programs
Unit-1(PRINCIPLES OF
1-12
PROGRAMMING LANGUAGES)
Evaluation Criteria: Others
• Portability
– The ease with which programs can be moved
from one implementation to another.
• Generality
– The applicability to a wide range of
applications.
• Well-definedness
– The completeness and precision of the
language’s official definition.
Unit-1(PRINCIPLES OF
1-13
PROGRAMMING LANGUAGES)
❖Influences on Language Design
• Computer Architecture
– Languages are developed around the prevalent
computer architecture, known as the von
Neumann architecture
• Programming Methodologies
– New software development methodologies (e.g.,
object-oriented software development) led to
new programming paradigms and by extension,
new programming languages

Unit-1(PRINCIPLES OF
1-14
PROGRAMMING LANGUAGES)
❖Computer Architecture Influence
• Well-known computer architecture: Von Neumann
• Imperative languages, most dominant, because of von
Neumann computers
– Data and programs stored in memory
– Memory is separate from CPU
– Instructions and data are piped from memory to
CPU
– Basis for imperative languages
• Variables model memory cells
• Assignment statements model piping
• Iteration is efficient

Unit-1(PRINCIPLES OF
1-15
PROGRAMMING LANGUAGES)
❖The Von Neumann Architecture

Unit-1(PRINCIPLES OF
1-16
PROGRAMMING LANGUAGES)
❖The Von Neumann Architecture
• Fetch-execute-cycle (on a von Neumann
architecture computer)

initialize the program counter


repeat forever
fetch the instruction pointed by the counter
increment the counter
decode the instruction
execute the instruction
end repeat

Unit-1(PRINCIPLES OF
1-17
PROGRAMMING LANGUAGES)
❖Programming Methodologies
Influences
• 1950s and early 1960s: Simple applications; worry about
machine efficiency
• Late 1960s: People efficiency became important;
readability,
better control structures
– structured programming
– top-down design and step-wise refinement
• Late 1970s: Process-oriented to data-oriented
– data abstraction
• Middle 1980s: Object-oriented programming
– Data abstraction + inheritance + polymorphism

Unit-1(PRINCIPLES OF
1-18
PROGRAMMING LANGUAGES)
❖Language Categories
• Imperative
– Central features are variables, assignment statements, and iteration
– Include languages that support object-oriented programming
– Include scripting languages
– Include the visual languages
– Examples: C, Java, Perl, JavaScript, Visual BASIC .NET, C++
• Functional
– Main means of making computations is by applying functions to given
parameters
– Examples: LISP, Scheme
• Logic
– Rule-based (rules are specified in no particular order)
– Example: Prolog
• Markup/programming hybrid
– Markup languages extended to support some programming
– Examples: JSTL, XSLT

Unit-1(PRINCIPLES OF
1-19
PROGRAMMING LANGUAGES)
❖Language Design Trade-Offs
• Reliability vs. cost of execution
– Example: Java demands all references to array elements be checked
for proper indexing, which leads to increased execution costs

• Readability vs. writability


Example: APL provides many powerful operators (and a large number of
new symbols), allowing complex computations to be written in a
compact program but at the cost of poor readability

• Writability (flexibility) vs. reliability


– Example: C++ pointers are powerful and very flexible but are
unreliable

Unit-1(PRINCIPLES OF
1-20
PROGRAMMING LANGUAGES)
❖Implementation Methods
• Compilation
– Programs are translated into machine language

• Pure Interpretation
– Programs are interpreted by another program known as an interpreter

• Hybrid Implementation Systems


– A compromise between compilers and pure interpreters

Unit-1(PRINCIPLES OF
1-21
PROGRAMMING LANGUAGES)
❖Layered View of Computer
The operating system
and language
implementation are
layered over
machine interface of
a computer

Unit-1(PRINCIPLES OF
1-22
PROGRAMMING LANGUAGES)
Compilation
• Translate high-level program (source language) into machine
code (machine language)
• Slow translation, fast execution
• Compilation process has several phases:
– lexical analysis: converts characters in the source program into lexical
units
– syntax analysis: transforms lexical units into parse trees which
represent the syntactic structure of program
– Semantics analysis: generate intermediate code
– code generation: machine code is generated

Unit-1(PRINCIPLES OF
1-23
PROGRAMMING LANGUAGES)
The Compilation Process

Unit-1(PRINCIPLES OF
1-24
PROGRAMMING LANGUAGES)
Additional Compilation Terminologies

• Load module (executable image): the user and


system code together
• Linking and loading: the process of collecting
system program units and linking them to a
user program

Unit-1(PRINCIPLES OF
1-25
PROGRAMMING LANGUAGES)
Von Neumann Bottleneck
• Connection speed between a computer’s
memory and its processor determines the speed
of a computer
• Program instructions often can be executed much
faster than the speed of the connection; the
connection speed thus results in a bottleneck
• Known as the von Neumann bottleneck; it is the
primary limiting factor in the speed of computers

Unit-1(PRINCIPLES OF
1-26
PROGRAMMING LANGUAGES)
Pure Interpretation
• No translation
• Easier implementation of programs (run-time errors can
easily and immediately be displayed)
• Slower execution (10 to 100 times slower than compiled
programs)
• Often requires more space
• Now rare for traditional high-level languages
• Significant comeback with some Web scripting languages
(e.g., JavaScript, PHP)

Unit-1(PRINCIPLES OF
1-27
PROGRAMMING LANGUAGES)
Pure Interpretation Process

Unit-1(PRINCIPLES OF
1-28
PROGRAMMING LANGUAGES)
Hybrid Implementation Systems
• A compromise between compilers and pure
interpreters
• A high-level language program is translated to an
intermediate language that allows easy
interpretation
• Faster than pure interpretation
• Examples
– Perl programs are partially compiled to detect errors before
interpretation
– Initial implementations of Java were hybrid; the intermediate form, byte
code, provides portability to any machine that has a byte code interpreter
and a run-time system (together, these are called Java Virtual Machine)

Unit-1(PRINCIPLES OF
1-29
PROGRAMMING LANGUAGES)
Hybrid Implementation Process

Unit-1(PRINCIPLES OF
1-30
PROGRAMMING LANGUAGES)
Just-in-Time Implementation Systems

• Initially translate programs to an intermediate language


• Then compile the intermediate language of the subprograms
into machine code when they are called
• Machine code version is kept for subsequent calls
• JIT systems are widely used for Java programs
• .NET languages are implemented with a JIT system

Unit-1(PRINCIPLES OF
1-31
PROGRAMMING LANGUAGES)
Preprocessors
• Preprocessor macros (instructions) are
commonly used to specify that code from
another file is to be included
• A preprocessor processes a program
immediately before the program is compiled
to expand embedded preprocessor
macros
• A well-known example: C preprocessor
– expands #include, #define, and similar
macros
Unit-1(PRINCIPLES OF
1-32
PROGRAMMING LANGUAGES)
CONCEPTS
• Introduction
• Primitive Data Types
• Character String Types
• User-Defined Ordinal Types
• Array Types
• Associative Arrays
• Record Types
• Union Types
• Pointer and Reference Types

Unit-2(PRINCIPLES OF
1-33
PROGRAMMING LANGUAGES)
CONCEPTS
● Introduction
● Names
● Variables
● The concept of binding
● Scope
● Scope and lifetime
● Referencing Environments
● Named constants

Unit-2(PRINCIPLES OF
1-34
PROGRAMMING LANGUAGES)
Introduction
• A data type defines a collection of data
objects and a set of predefined operations on
those objects
• A descriptor is the collection of the attributes
of a variable
• An object represents an instance of a user-
defined (abstract data) type
• One design issue for all data types: What
operations are defined and how are
they specified?

Unit-2(PRINCIPLES OF
1-35
PROGRAMMING LANGUAGES)
Primitive Data Types
• Almost all programming languages provide a
set of primitive data types
• Primitive data types: Those not defined in
terms of other data types
• Some primitive data types are merely
reflections of the hardware
• Others require only a little non-hardware
support for their implementation

Unit-2(PRINCIPLES OF
1-36
PROGRAMMING LANGUAGES)
Primitive Data Types: 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
• Java’s signed integer sizes: byte, short,
int, long

Unit-2(PRINCIPLES OF
1-37
PROGRAMMING LANGUAGES)
Primitive Data Types: Floating Point
• Model real numbers, but only as
approximations
• Languages for scientific use support at least
two floating-point types (e.g., float and
double; sometimes more
• Usually exactly like the hardware, but not
always
• IEEE Floating-Point
Standard 754
Unit-2(PRINCIPLES OF
1-38
PROGRAMMING LANGUAGES)
Primitive Data Types: Complex
• Some languages support a complex type, e.g.,
C99, Fortran, and Python
• Each value consists of two floats, the real part
and the imaginary part
• Literal form (in Python):
(7 + 3j), where 7 is the real part and 3 is
the imaginary part

Unit-2(PRINCIPLES OF
1-39
PROGRAMMING LANGUAGES)
Primitive Data Types: Decimal
• For business applications (money)
– Essential to COBOL
– C# offers a decimal data type
• Store a fixed number of decimal digits, in
coded form (BCD)
• Advantage: accuracy
• Disadvantages: limited range, wastes
memory
Unit-2(PRINCIPLES OF
1-40
PROGRAMMING LANGUAGES)
Primitive Data Types: Boolean
• Simplest of all
• Range of values: two elements, one for “true”
and one for “false”
• Could be implemented as bits, but often as
bytes
– Advantage: readability

Unit-2(PRINCIPLES OF
1-41
PROGRAMMING LANGUAGES)
Primitive Data Types: Character
• Stored as numeric codings
• Most commonly used coding: ASCII
• An alternative, 16-bit coding: Unicode (UCS-2)
– Includes characters from most natural languages
– Originally used in Java
– C# and JavaScript also support Unicode
• 32-bit Unicode (UCS-4)
– Supported by Fortran, starting with 2003

Unit-2(PRINCIPLES OF
1-42
PROGRAMMING LANGUAGES)
Character String Types
• Values are sequences of characters
• Design issues:
– Is it a primitive type or just a special kind of array?
– Should the length of strings be static or dynamic?

Unit-2(PRINCIPLES OF
1-43
PROGRAMMING LANGUAGES)
Character String Types Operations
• Typical operations:
– Assignment and copying
– Comparison (=, >, etc.)
– Catenation
– Substring reference
– Pattern matching

Unit-2(PRINCIPLES OF
1-44
PROGRAMMING LANGUAGES)
Character String Type in Certain Languages

• C and C++
– Not primitive
– Use char arrays and a library of functions that provide
operations
• SNOBOL4 (a string manipulation language)
– Primitive
– Many operations, including elaborate pattern matching
• Fortran and Python
– Primitive type with assignment and several operations
• Java
– Primitive via the String class
• Perl, JavaScript, Ruby, and PHP
- Provide built-in pattern matching, using regular
expressions

Unit-2(PRINCIPLES OF
1-45
PROGRAMMING LANGUAGES)
Character String Length Options
• Static: COBOL, Java’s String class
• Limited Dynamic Length: C and C++
– In these languages, a special character is used to
indicate the end of a string’s characters, rather
than maintaining the length
• Dynamic (no maximum): SNOBOL4, Perl,
JavaScript
• Ada supports all three string length
options
Unit-2(PRINCIPLES OF
1-46
PROGRAMMING LANGUAGES)
Character String Type Evaluation
• 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?

Unit-2(PRINCIPLES OF
1-47
PROGRAMMING LANGUAGES)
Character String Implementation
• Static length: compile-time descriptor
• Limited dynamic length: may need a run-time
descriptor for length (but not in C and C++)
• Dynamic length: need run-time descriptor;
allocation/de-allocation is the biggest
implementation problem

Unit-2(PRINCIPLES OF
1-48
PROGRAMMING LANGUAGES)
Compile- and Run-Time Descriptors

Compile-time Run-time
descriptor descriptor for
for static limited dynamic
strings strings
Unit-2(PRINCIPLES OF
1-49
PROGRAMMING LANGUAGES)
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
• Examples of primitive ordinal types in Java
– integer
– char
– boolean

Unit-2(PRINCIPLES OF
1-50
PROGRAMMING LANGUAGES)
Enumeration Types
• All possible values, which are named
constants, are provided in the definition
• C# example
enum days {mon, tue, wed, thu, fri, sat,
sun};
• Design issues
– Is an enumeration constant allowed to appear in
more than one type definition, and if so, how is
the type of an occurrence of that constant
checked?
– Are enumeration values coerced to integer?
– Any other type coerced to an enumeration type?
Unit-2(PRINCIPLES OF
1-51
PROGRAMMING LANGUAGES)
Evaluation of Enumerated Type
• Aid to readability, e.g., no need to code a color
as a number
• Aid to reliability, e.g., compiler can check:
– operations (don’t allow colors to be added)
– No enumeration variable can be assigned a value
outside its defined range
– Ada, C#, and Java 5.0 provide better support for
enumeration than C++ because enumeration type
variables in these languages are not coerced into
integer types
Unit-2(PRINCIPLES OF
1-52
PROGRAMMING LANGUAGES)
Subrange Types
• An ordered contiguous subsequence of an
ordinal type
– Example: 12..18 is a subrange of integer type
• Ada’s design
type Days is (mon, tue, wed, thu, fri, sat, sun);
subtype Weekdays is Days range mon..fri;
subtype Index is Integer range 1..100;

Day1: Days;
Day2: Weekday;
Day2 := Day1;
Unit-2(PRINCIPLES OF
1-53
PROGRAMMING LANGUAGES)
Subrange Evaluation
• Aid to readability
– Make it clear to the readers that variables of
subrange can store only certain range of values
• Reliability
– Assigning a value to a subrange variable that is
outside the specified range is detected as an error

Unit-2(PRINCIPLES OF
1-54
PROGRAMMING LANGUAGES)
Implementation of User-Defined Ordinal Types

• Enumeration types are implemented as


integers
• Subrange types are implemented like the
parent types with code inserted (by the
compiler) to restrict assignments to subrange
variables

Unit-2(PRINCIPLES OF
1-55
PROGRAMMING LANGUAGES)
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.

Unit-2(PRINCIPLES OF
1-56
PROGRAMMING LANGUAGES)
Array Design Issues
• What types are legal for subscripts?
• Are subscripting expressions in element
references range checked?
• When are subscript ranges bound?
• When does allocation take place?
• What is the maximum number of
subscripts?
• Can array objects be initialized?
• Are any kind of slices supported?
Unit-2(PRINCIPLES OF
1-57
PROGRAMMING LANGUAGES)
Array Indexing
• Indexing (or subscripting) is a mapping from
indices to elements
array_name (index_value_list) → an element

• Index Syntax
– FORTRAN, PL/I, Ada use parentheses
• Ada explicitly uses parentheses to show uniformity
between array references and function calls because
both are mappings
– Most other languages use brackets

Unit-2(PRINCIPLES OF
1-58
PROGRAMMING LANGUAGES)
Arrays Index (Subscript) Types
• FORTRAN, C: integer only
• Ada: integer or enumeration (includes Boolean and char)
• Java: integer types only
• Index range checking
- C, C++, Perl, and Fortran do not
specify range checking
- Java, ML, C# specify range checking
- In Ada, the default is to require
range checking, but it can be
turned off

Unit-2(PRINCIPLES OF
1-59
PROGRAMMING LANGUAGES)
Subscript Binding and Array Categories

• Static: subscript ranges are statically bound


and storage allocation is static (before run-
time)
– Advantage: efficiency (no dynamic allocation)
• Fixed stack-dynamic: subscript ranges are
statically bound, but the allocation is done at
declaration time
– Advantage: space efficiency

Unit-2(PRINCIPLES OF
1-60
PROGRAMMING LANGUAGES)
Subscript Binding and Array Categories
(continued)
• Stack-dynamic: subscript ranges are
dynamically bound and the storage allocation
is dynamic (done at run-time)
– Advantage: flexibility (the size of an array need not
be known until the array is to be used)
• Fixed heap-dynamic: similar to fixed stack-
dynamic: storage binding is dynamic but fixed
after allocation (i.e., binding is done when
requested and storage is allocated from heap,
not stack)
Unit-2(PRINCIPLES OF
1-61
PROGRAMMING LANGUAGES)
Subscript Binding and Array Categories
(continued)

• Heap-dynamic: binding of subscript ranges


and storage allocation is dynamic and can
change any number of times
– Advantage: flexibility (arrays can grow or shrink
during program execution)

Unit-2(PRINCIPLES OF
1-62
PROGRAMMING LANGUAGES)
Subscript Binding and Array Categories
(continued)
• C and C++ arrays that include static
modifier are static
• C and C++ arrays without static modifier
are fixed stack-dynamic
• C and C++ provide fixed heap-dynamic arrays
• C# includes a second array class ArrayList
that provides fixed heap-dynamic
• Perl, JavaScript, Python, and Ruby support
heap-dynamic arrays
Unit-2(PRINCIPLES OF
1-63
PROGRAMMING LANGUAGES)
Array Initialization
• Some language allow initialization at the time of
storage allocation
– C, C++, Java, C# example
int list [] = {4, 5, 7, 83}
– Character strings in C and C++
char name [] = “freddie”;
– Arrays of strings in C and C++
char *names [] = {“Bob”, “Jake”,
“Joe”];
– Java initialization of String objects
String[] names = {“Bob”, “Jake”,
“Joe”};
Unit-2(PRINCIPLES OF
1-64
PROGRAMMING LANGUAGES)
Heterogeneous Arrays
• A heterogeneous array is one in which the
elements need not be of the same type
• Supported by Perl, Python, JavaScript, and
Ruby

Unit-2(PRINCIPLES OF
1-65
PROGRAMMING LANGUAGES)
Array Initialization
• C-based languages
– int list [] = {1, 3, 5, 7}
– char *names [] = {“Mike”, “Fred”,“Mary Lou”};

• Ada
– List : array (1..5) of Integer :=
(1 => 17, 3 => 34, others => 0);
• Python
– List comprehensions
list = [x ** 2 for x in range(12) if x % 3 == 0]
puts [0, 9, 36, 81] in list

Unit-2(PRINCIPLES OF
1-66
PROGRAMMING LANGUAGES)
Arrays Operations
• APL provides the most powerful array processing operations
for vectors and matrixes as well as unary operators (for
example, to reverse column elements)
• Ada allows array assignment but also catenation
• Python’s array assignments, but they are only reference
changes. Python also supports array catenation and element
membership operations
• Ruby also provides array catenation
• Fortran provides elemental operations because they are
between pairs of array elements
– For example, + operator between two arrays results in an array of the
sums of the element pairs of the two arrays

Unit-2(PRINCIPLES OF
1-67
PROGRAMMING LANGUAGES)
Rectangular and Jagged Arrays
• A rectangular array is a multi-dimensioned array
in which all of the rows have the same number of
elements and all columns have the same
number of elements
• A jagged matrix has rows with varying number of
elements
– Possible when multi-dimensioned arrays actually
appear as arrays of arrays
• C, C++, and Java support jagged arrays
• Fortran, Ada, and C# support rectangular arrays
(C# also supports jagged arrays)
Unit-2(PRINCIPLES OF
1-68
PROGRAMMING LANGUAGES)
Slices
• A slice is some substructure of an array;
nothing more than a referencing mechanism
• Slices are only useful in languages that have
array operations

Unit-2(PRINCIPLES OF
1-69
PROGRAMMING LANGUAGES)
Slice Examples
• Fortran 95
Integer, Dimension (10) :: Vector
Integer, Dimension (3, 3) :: Mat
Integer, Dimension (3, 3) :: Cube

Vector (3:6) is a four element array

• Ruby supports slices with the slice method


[Link](2, 2) returns the third and fourth
elements of list Unit-2(PRINCIPLES OF
PROGRAMMING LANGUAGES)
1-70
Slices Examples in Fortran 95

Unit-2(PRINCIPLES OF
1-71
PROGRAMMING LANGUAGES)
Implementation of Arrays
• Access function maps subscript expressions to
an address in the array
• Access function for single-dimensioned arrays:
address(list[k]) = address (list[lower_bound])
+ ((k-lower_bound) * element_size)

Unit-2(PRINCIPLES OF
1-72
PROGRAMMING LANGUAGES)
Accessing Multi-dimensioned Arrays

• Two common ways:


– Row major order (by rows) – used in most
languages
– column major order (by columns) – used in
Fortran

Unit-2(PRINCIPLES OF
1-73
PROGRAMMING LANGUAGES)
Locating an Element in a Multi-dimensioned
Array
•General format
Location (a[I,j]) = address of a [row_lb,col_lb] + (((I -
row_lb) * n) + (j - col_lb)) * element_size

Unit-2(PRINCIPLES OF
1-74
PROGRAMMING LANGUAGES)
Compile-Time Descriptors

Single-dimensioned array Multi-dimensional array

Unit-2(PRINCIPLES OF
1-75
PROGRAMMING LANGUAGES)
Associative Arrays
• An associative array is an unordered
collection of data elements that are indexed
by an equal number of values called keys
– User-defined keys must be stored
• Design issues:
- What is the form of references to elements?
- Is the size static or dynamic?
• Built-in type in Perl, Python, Ruby, and Lua
– In Lua, they are supported by tables

Unit-2(PRINCIPLES OF
1-76
PROGRAMMING LANGUAGES)
Associative Arrays in Perl
• Names begin with %; literals are delimited
by parentheses
%hi_temps = ("Mon" => 77, "Tue" =>
79, “Wed” => 65, …);
• Subscripting is done using braces and keys
$hi_temps{"Wed"} = 83;
– Elements can be removed with delete
delete $hi_temps{"Tue"};

Unit-2(PRINCIPLES OF
1-77
PROGRAMMING LANGUAGES)
Record Types
• A record is a possibly heterogeneous
aggregate of data elements in which the
individual elements are identified by names
• Design issues:
– What is the syntactic form of references to the
field?
– Are elliptical references allowed

Unit-2(PRINCIPLES OF
1-78
PROGRAMMING LANGUAGES)
Definition of Records in COBOL
• COBOL uses level numbers to show nested
records; others use recursive definition
01 EMP-REC.
02 EMP-NAME.
05 FIRST PIC X(20).
05 MID PIC X(10).
05 LAST PIC X(20).
02 HOURLY-RATE PIC 99V99.

Unit-2(PRINCIPLES OF
1-79
PROGRAMMING LANGUAGES)
Definition of Records in Ada
• Record structures are indicated in an orthogonal
way
type Emp_Rec_Type is record
First: String (1..20);
Mid: String (1..10);
Last: String (1..20);
Hourly_Rate: Float;
end record;
Emp_Rec: Emp_Rec_Type;

Unit-2(PRINCIPLES OF
1-80
PROGRAMMING LANGUAGES)
References to Records
• Record field references
1. COBOL
field_name OF record_name_1 OF ... OF record_name_n
2. Others (dot notation)
record_name_1.record_name_2. ... record_name_n.field_name

• Fully qualified references must include all record names

• Elliptical references allow leaving out record names as long as the


reference is unambiguous, for example in COBOL
FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are
elliptical references to the employee’s first name

Unit-2(PRINCIPLES OF
1-81
PROGRAMMING LANGUAGES)
Operations on Records
• Assignment is very common if the types are
identical
• Ada allows record comparison
• Ada records can be initialized with aggregate
literals
• COBOL provides MOVE CORRESPONDING
– Copies a field of the source record to the
corresponding field in the target record

Unit-2(PRINCIPLES OF
1-82
PROGRAMMING LANGUAGES)
Evaluation and Comparison to
Arrays
• Records are used when collection of data
values is heterogeneous
• Access to array elements is much slower than
access to record fields, because subscripts are
dynamic (field names are static)
• Dynamic subscripts could be used with record
field access, but it would disallow type
checking and it would be much slower
Unit-2(PRINCIPLES OF
1-83
PROGRAMMING LANGUAGES)
Implementation of Record Type

Offset address relative to the


beginning of the records is
associated with each field

Unit-2(PRINCIPLES OF
1-84
PROGRAMMING LANGUAGES)
Unions Types
• A union is a type whose variables are allowed
to store different type values at different
times during execution
• Design issues
– Should type checking be required?
– Should unions be embedded in records?

Unit-2(PRINCIPLES OF
1-85
PROGRAMMING LANGUAGES)
Discriminated vs. Free Unions
• Fortran, C, and C++ provide union constructs
in which there is no language support for type
checking; the union in these languages is
called free union
• Type checking of unions require that each
union include a type indicator called a
discriminant
– Supported by Ada

Unit-2(PRINCIPLES OF
1-86
PROGRAMMING LANGUAGES)
Ada Union Types
type Shape is (Circle, Triangle, Rectangle);
type Colors is (Red, Green, Blue);
type Figure (Form: Shape) is record
Filled: Boolean;
Color: Colors;
case Form is
when Circle
=> Diameter:
Float;
when
Triangle =>
Leftside, Rightside: Integer;
Angle: Float;
when Rectangle => Side1, Side2: Integer;
end case;
Unit-2(PRINCIPLES OF
end record; PROGRAMMING LANGUAGES)
1-87
Ada Union Type Illustrated

A discriminated union of three shape variables

Unit-2(PRINCIPLES OF
1-88
PROGRAMMING LANGUAGES)
Evaluation of Unions
• Free unions are unsafe
– Do not allow type checking
• Java and C# do not support unions
– Reflective of growing concerns for safety in
programming language
• Ada’s descriminated unions are safe

Unit-2(PRINCIPLES OF
1-89
PROGRAMMING LANGUAGES)
Pointer and Reference Types
• A pointer type variable has a range of values
that consists of memory addresses and a
special value, nil
• Provide the power of indirect addressing
• Provide a way to manage dynamic memory
• A pointer can be used to access a location in
the area where storage is dynamically created
(usually called a heap)

Unit-2(PRINCIPLES OF
1-90
PROGRAMMING LANGUAGES)
Design Issues of Pointers
• What are the scope of and lifetime of a
pointer variable?
• What is the lifetime of a heap-dynamic
variable?
• Are pointers restricted as to the type of value
to which they can point?
• Are pointers used for dynamic storage
management, indirect addressing, or both?
• Should the language support pointer types,
reference types, or both?
Unit-2(PRINCIPLES OF
1-91
PROGRAMMING LANGUAGES)
Pointer Operations
• Two fundamental operations: assignment and
dereferencing
• Assignment is used to set a pointer variable’s
value to some useful address
• Dereferencing yields the value stored at the
location represented by the pointer’s value
– Dereferencing can be explicit or implicit
– C++ uses an explicit operation via *
j = *ptr
sets j to the value located at ptr
Unit-2(PRINCIPLES OF
1-92
PROGRAMMING LANGUAGES)
Pointer Assignment Illustrated

The assignment operation j = *ptr


Unit-2(PRINCIPLES OF
1-93
PROGRAMMING LANGUAGES)
Problems with Pointers
• Dangling pointers (dangerous)
– A pointer points to a heap-dynamic variable that has been
deallocated
• Lost heap-dynamic variable
– An allocated heap-dynamic variable that is no longer accessible to the
user program (often called garbage)
• Pointer p1 is set to point to a newly created heap-dynamic variable
• Pointer p1 is later set to point to another newly created
heap- dynamic variable
• The process of losing heap-dynamic variables is called memory
leakage

Unit-2(PRINCIPLES OF
1-94
PROGRAMMING LANGUAGES)
Pointers in Ada
• Some dangling pointers are disallowed
because dynamic objects can be automatically
deallocated at the end of pointer's type scope
• The lost heap-dynamic variable problem is not
eliminated by Ada (possible with
UNCHECKED_DEALLOCATION)

Unit-2(PRINCIPLES OF
1-95
PROGRAMMING LANGUAGES)
Pointers in C and C++
• Extremely flexible but must be used with care
• Pointers can point at any variable regardless of when or where
it was allocated
• Used for dynamic storage management and addressing
• Pointer arithmetic is possible
• Explicit dereferencing and address-of operators
• Domain type need not be fixed (void *)
void * can point to any type and can be
type checked (cannot be de-referenced)

Unit-2(PRINCIPLES OF
1-96
PROGRAMMING LANGUAGES)
Pointer Arithmetic in C and C++
float stuff[100];
float *p;
p = stuff;

*(p+5) is equivalent stuff[5]


to and
p[5] stuff[i]
*(p+i) is equivalent and
to
p[i] Unit-2(PRINCIPLES OF
1-97
PROGRAMMING LANGUAGES)
Reference Types
• C++ includes a special kind of pointer type
called a reference type that is used primarily
for formal parameters
– Advantages of both pass-by-reference and pass-
by-value
• Java extends C++’s reference variables and
allows them to replace pointers entirely
– References are references to objects, rather than
being addresses
• C# includes both the references of Java and
the pointers of C++

Unit-2(PRINCIPLES OF
1-98
PROGRAMMING LANGUAGES)
Evaluation of Pointers
• Dangling pointers and dangling objects are
problems as is heap management
• Pointers are like goto's--they widen the range
of cells that can be accessed by a variable
• Pointers or references are necessary for
dynamic data structures--so we can't design a
language without them

Unit-2(PRINCIPLES OF
1-99
PROGRAMMING LANGUAGES)
Representations of Pointers
• Large computers use single values
• Intel microprocessors use segment and
offset

Unit-2(PRINCIPLES OF
1-100
PROGRAMMING LANGUAGES)
Dangling Pointer Problem
• Tombstone: extra heap cell that is a pointer to the heap-
dynamic variable
– The actual pointer variable points only at tombstones
– When heap-dynamic variable de-allocated, tombstone remains but set
to nil
– Costly in time and space
. Locks-and-keys: Pointer values are represented as (key, address)
pairs
– Heap-dynamic variables are represented as variable plus cell for
integer lock value
– When heap-dynamic variable allocated, lock value is created and
placed in lock cell and key cell of pointer

Unit-2(PRINCIPLES OF
1-101
PROGRAMMING LANGUAGES)
Heap Management
• A very complex run-time process
• Single-size cells vs. variable-size cells
• Two approaches to reclaim garbage
– Reference counters (eager
approach): reclamation is gradual
– Mark-sweep (lazy approach): reclamation
occurs when the list of variable space becomes
empty

Unit-2(PRINCIPLES OF
1-102
PROGRAMMING LANGUAGES)
Reference Counter
• Reference counters: maintain a counter in
every cell that store the number of pointers
currently pointing at the cell
– Disadvantages: space required, execution time
required, complications for cells connected
circularly
– Advantage: it is intrinsically incremental, so
significant delays in the application execution are
avoided

Unit-2(PRINCIPLES OF
1-103
PROGRAMMING LANGUAGES)
Mark-Sweep
• The run-time system allocates storage cells as requested
and disconnects pointers from cells as necessary; mark-
sweep then begins
– Every heap cell has an extra bit used by collection algorithm
– All cells initially set to garbage
– All pointers traced into heap, and reachable cells marked as not
garbage
– All garbage cells returned to list of available cells
– Disadvantages: in its original form, it was done too infrequently.
When done, it caused significant delays in application execution.
Contemporary mark-sweep algorithms avoid this by doing it more
often—called incremental mark-sweep

Unit-2(PRINCIPLES OF
1-104
PROGRAMMING LANGUAGES)
Marking Algorithm

Unit-2(PRINCIPLES OF
1-105
PROGRAMMING LANGUAGES)
Variable-Size Cells
• All the difficulties of single-size cells plus more
• Required by most programming languages
• If mark-sweep is used, additional problems
occur
– The initial setting of the indicators of all cells in
the heap is difficult
– The marking process in nontrivial
– Maintaining the list of available space is another
source of overhead

Unit-2(PRINCIPLES OF
1-106
PROGRAMMING LANGUAGES)
Type Checking
• Generalize the concept of operands and operators to include subprograms
and assignments

• 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

Unit-2(PRINCIPLES OF
1-107
PROGRAMMING LANGUAGES)
Type Checking (continued)
• If all type bindings are static, nearly all type
checking can be static
• If type bindings are dynamic, type checking
must be dynamic
• A programming language is strongly typed if
type errors are always detected
• Advantage of strong typing: allows the
detection of the misuses of variables that
result in type errors
Unit-2(PRINCIPLES OF
1-108
PROGRAMMING LANGUAGES)
Strong Typing
Language examples:
– FORTRAN 95 is not: parameters, EQUIVALENCE
– C and C++ are not: parameter type checking can
be avoided; unions are not type checked
– Ada is, almost (UNCHECKED CONVERSION
is loophole)
(Java and C# are similar to Ada)

Unit-2(PRINCIPLES OF
1-109
PROGRAMMING LANGUAGES)
Strong Typing (continued)
• Coercion rules strongly affect strong typing--
they can weaken it considerably (C++ versus
Ada)

• Although Java has just half the assignment


coercions of C++, its strong typing is still far
less effective than that of Ada

Unit-2(PRINCIPLES OF
1-110
PROGRAMMING LANGUAGES)
Name Type Equivalence
• Name type equivalence means the two
variables have equivalent types if they are in
either the same declaration or in declarations
that use the same type name
• Easy to implement but highly restrictive:
– Subranges of integer types are not equivalent with
integer types
– Formal parameters must be the same type as their
corresponding actual parameters
Unit-2(PRINCIPLES OF
1-111
PROGRAMMING LANGUAGES)
Structure Type Equivalence
• Structure type equivalence means that two
variables have equivalent types if their types
have identical structures
• More flexible, but harder to implement

Unit-2(PRINCIPLES OF
1-112
PROGRAMMING LANGUAGES)
Type Equivalence (continued)
• Consider the problem of two structured types:
– Are two record types equivalent if they are
structurally the same but use different field
names?
– Are two array types equivalent if they are the
same except that the subscripts are different?
(e.g. [1..10] and [0..9])
– Are two enumeration types equivalent if their
components are spelled differently?
– With structural type equivalence, you cannot
differentiate between types of the same structure
(e.g. different units of speed, both float)

Unit-2(PRINCIPLES OF
1-113
PROGRAMMING LANGUAGES)
Variable Attributes (continued)
• Type Inferencing (ML, Miranda, and Haskell)
– Rather than by assignment statement, types are
determined (by the compiler) from the context of
the reference
• Storage Bindings & Lifetime
– Allocation - getting a cell from some pool of
available cells
– Deallocation - putting a cell back into the
pool
• The lifetime of a variable is the time during
which it is bound to a particular memory cell
Unit-2(PRINCIPLES OF
1-114
PROGRAMMING LANGUAGES)
Categories of Variables by Lifetimes
• Static--bound to memory cells before
execution begins and remains bound to the
same memory cell throughout execution, e.g.,
C and C++ static variables
– Advantages: efficiency (direct
addressing), history-sensitive subprogram
support
– Disadvantage: lack of flexibility (no
recursion)

Unit-2(PRINCIPLES OF
1-115
PROGRAMMING LANGUAGES)
Categories of Variables by Lifetimes
• Stack-dynamic--Storage bindings are created for variables
when their declaration statements are elaborated.
(A declaration is elaborated when the executable code
associated with it is executed)
• If scalar, all attributes except address are statically
bound
– local variables in C subprograms and Java methods
• Advantage: allows recursion; conserves storage
• Disadvantages:
– Overhead of allocation and deallocation
– Subprograms cannot be history sensitive
– Inefficient references (indirect addressing)
Unit-2(PRINCIPLES OF
1-116
PROGRAMMING LANGUAGES)
UNIT -2
Expressions & Statements
• Introduction
• Arithmetic Expressions
• Overloaded Operators
• Type Conversions
• Relational and Boolean Expressions
• Short-Circuit Evaluation
• Assignment Statements
• Mixed-Mode Assignment

Unit-2(PRINCIPLES OF
1-117
PROGRAMMING LANGUAGES)
Introduction
• Expressions are the fundamental means of
specifying computations in a
programming language
• To understand expression evaluation, need to
be familiar with the orders of operator and
operand evaluation
• Essence of imperative languages is dominant
role of assignment statements

Unit-2(PRINCIPLES OF
1-118
PROGRAMMING LANGUAGES)
Arithmetic Expressions
• Arithmetic evaluation was one of the
motivations for the development of the first
programming languages
• Arithmetic expressions consist of operators,
operands, parentheses, and function calls

Unit-2(PRINCIPLES OF
1-119
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Design Issues

• Design issues for arithmetic expressions


– Operator precedence rules?
– Operator associativity rules?
– Order of operand evaluation?
– Operand evaluation side effects?
– Operator overloading?
– Type mixing in expressions?

Unit-2(PRINCIPLES OF
1-120
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Operators
• A unary operator has one operand
• A binary operator has two operands
• A ternary operator has three operands

Unit-2(PRINCIPLES OF
1-121
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Operator Precedence
Rules
• The operator precedence rules for
expression evaluation define the order in
which “adjacent” operators of different
precedence levels are evaluated
• Typical precedence levels
– parentheses
– unary operators
– ** (if the language supports it)
– *, /
– +, -
Unit-2(PRINCIPLES OF
1-122
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Operator Associativity
Rule
• The operator associativity rules for expression evaluation
define the order in which adjacent operators with the same
precedence level are evaluated
• Typical associativity rules
– Left to right, except **, which is right to left
– Sometimes unary operators associate right to left (e.g., in
FORTRAN)
• APL is different; all operators have equal precedence and all
operators associate right to left
• Precedence and associativity rules can be overriden with
parentheses

Unit-2(PRINCIPLES OF
1-123
PROGRAMMING LANGUAGES)
Ruby Expressions
• All arithmetic, relational, and assignment
operators, as well as array indexing, shifts, and
bit-wise logic operators, are implemented as
methods
- One result of this is that these operators can all
be overriden by application programs

Unit-2(PRINCIPLES OF
1-124
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Conditional Expressions

• Conditional Expressions
– C-based languages (e.g., C, C++)
– An example:
average = (count == 0)? 0 : sum / count

– Evaluates as if written like


if (count == 0)
average = 0
else
average =
sum /count

Unit-2(PRINCIPLES OF
1-125
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Operand Evaluation
Order

• Operand evaluation order


1. Variables: fetch the value from memory
2. Constants: sometimes a fetch from memory;
sometimes the constant is in the machine
language instruction
3. Parenthesized expressions: evaluate all operands
and operators first
4. The most interesting case is when an operand is
a function call

Unit-2(PRINCIPLES OF
1-126
PROGRAMMING LANGUAGES)
Arithmetic Expressions: Potentials for Side
Effects
• Functional side effects: when a function changes a two-way
parameter or a non-local variable
• Problem with functional side effects:
– When a function referenced in an expression alters another operand
of the expression; e.g., for a parameter change:
a = 10;
/* assume that fun changes its parameter */
b = a + fun(&a);

Unit-2(PRINCIPLES OF
1-127
PROGRAMMING LANGUAGES)
Functional Side Effects
• Two possible solutions to the problem
1. Write the language definition to disallow functional side effects
• No two-way parameters in functions
• No non-local references in functions
• Advantage: it works!
• Disadvantage: inflexibility of one-way parameters and lack of non-
local references
2. Write the language definition to demand that operand evaluation
order be fixed
• Disadvantage: limits some compiler optimizations
• Java requires that operands appear to be evaluated in left-to-
right
order

Unit-2(PRINCIPLES OF
1-128
PROGRAMMING LANGUAGES)
Overloaded Operators
• Use of an operator for more than one purpose
is called operator overloading
• Some are common (e.g., + for int and
float)
• Some are potential trouble (e.g., * in C
and C++)
– Loss of compiler error detection (omission of an
operand should be a detectable error)
– Some loss of readability

Unit-2(PRINCIPLES OF
1-129
PROGRAMMING LANGUAGES)
Overloaded Operators (continued)
• C++ and C# allow user-defined overloaded
operators
• Potential problems:
– Users can define nonsense operations
– Readability may suffer, even when the operators
make sense

Unit-2(PRINCIPLES OF
1-130
PROGRAMMING LANGUAGES)
Type Conversions
• A narrowing conversion is one that converts
an object to a type that cannot include all of
the values of the original type e.g., float
to int
• A widening conversion is one in which an
object is converted to a type that can include
at least approximations to all of the values
of the original type e.g., int
to float

Unit-2(PRINCIPLES OF
1-131
PROGRAMMING LANGUAGES)
Type Conversions: Mixed Mode
• A mixed-mode expression is one that has operands of
different types
• A coercion is an implicit type conversion
• Disadvantage of coercions:
– They decrease in the type error detection ability of the
compiler
• In most languages, all numeric types are coerced in
expressions, using widening conversions
• In Ada, there are virtually no coercions in
expressions

Unit-2(PRINCIPLES OF
1-132
PROGRAMMING LANGUAGES)
Explicit Type Conversions

• Called casting in C-based languages


• Examples
– C: (int)angle
– Ada: Float (Sum)

Note that Ada’s syntax is similar to that of


function calls

Unit-2(PRINCIPLES OF
1-133
PROGRAMMING LANGUAGES)
Type Conversions: Errors in Expressions

• Causes
– Inherent limitations of arithmetic
e.g., division by zero
– Limitations of computer arithmetic e.g.
overflow
• Often ignored by the run-time
system

Unit-2(PRINCIPLES OF
1-134
PROGRAMMING LANGUAGES)
Relational and Boolean Expressions
• Relational Expressions
– Use relational operators and operands of various
types
– Evaluate to some Boolean representation
– Operator symbols used vary somewhat among
languages (!=, /=, ~=, .NE., <>, #)
• JavaScript and PHP have two additional
relational operator, === and !==
- Similar to their cousins, == and !=, except that they do
not coerce their operands
Unit-2(PRINCIPLES OF
1-135
PROGRAMMING LANGUAGES)
Relational and Boolean Expressions
• Boolean Expressions
– Operands are Boolean and the result is Boolean
– Example operators

FORTRAN 77 FORTRAN 90 C Ada


.AND. and && and
.OR. or || or
.NOT. not ! not
xor
Unit-2(PRINCIPLES OF
1-136
PROGRAMMING LANGUAGES)
Relational and Boolean Expressions: No Boolean
Type in C

• C89 has no Boolean type--it uses int


type with 0 for false and nonzero for true
• One odd characteristic of C’s expressions:
a < b < c is a legal expression, but the result
is not what you might expect:
– Left operator is evaluated, producing 0 or 1
– The evaluation result is then compared with the
third operand (i.e., c)

Unit-2(PRINCIPLES OF
1-137
PROGRAMMING LANGUAGES)
Short Circuit Evaluation
• An expression in which the result is
determined without evaluating all of the
operands and/or operators
• Example: (13*a) * (b/13–1)
If a is zero, there is no need to evaluate
(b/13-1)
• Problem with non-short-circuit
evaluation
index = 1;
while (index <= length) && (LIST[index] !=
value)
index++;
– When index=length, LISTOF[index] will cause
Unit-2(PRINCIPLES
1-138
PROGRAMMING LANGUAGES)
an indexing
Short Circuit Evaluation
(continued)
• C, C++, and Java: use short-circuit evaluation for the usual
Boolean operators (&& and ||), but also provide
bitwise Boolean operators that are not short circuit (&
and |)
• Ada: programmer can specify either (short-circuit is specified
with and then and or else)
• Short-circuit evaluation exposes the potential problem of side
effects in expressions
e.g. (a > b) || (b++ / 3)

Unit-2(PRINCIPLES OF
1-139
PROGRAMMING LANGUAGES)
Assignment Statements
• The general syntax
<target_var> <assign_operator> <expression>
• The assignment operator
= FORTRAN, BASIC, the C-based languages
:= ALGOLs, Pascal, Ada
• = can be bad when it is overloaded for the
relational operator for equality (that’s why the
C-based languages use == as the relational
operator)

Unit-2(PRINCIPLES OF
1-140
PROGRAMMING LANGUAGES)
Assignment Statements: Conditional Targets

• Conditional targets (Perl)


($flag ? $total : $subtotal) = 0

Which is equivalent to

if ($flag){
$total = 0
} else {
$subtotal = 0
}

Unit-2(PRINCIPLES OF
1-141
PROGRAMMING LANGUAGES)
Assignment Statements: Compound Operators

• A shorthand method of specifying a


commonly needed form of assignment
• Introduced in ALGOL; adopted by C
• Example

a = a + b

is written as

a += b
Unit-2(PRINCIPLES OF
1-142
PROGRAMMING LANGUAGES)
Assignment Statements: Unary Assignment
Operators
• Unary assignment operators in C-based
languages combine increment and decrement
operations with assignment
• Examples
sum = ++count (count incremented, added
to
sum)
sum = count++ (count incremented, added
to
sum)
count++ (count incremented)
Unit-2(PRINCIPLES OF
-count++ (count incremented
PROGRAMMING LANGUAGES) then negated) 1-143
Assignment as an Expression
• In C, C++, and Java, the assignment statement
produces a result and can be used as operands
• An example:
while ((ch = getchar())!=
EOF){…}

ch = getchar() is carried out; the result


(assigned to ch) is used as a conditional value for
the while statement
Unit-2(PRINCIPLES OF
1-144
PROGRAMMING LANGUAGES)
List Assignments
• Perl and Ruby support list
assignments e.g.,
($first, $second, $third) = (20, 30,
40);

Unit-2(PRINCIPLES OF
1-145
PROGRAMMING LANGUAGES)
Mixed-Mode Assignment
• Assignment statements can also be mixed-
mode
• In Fortran, C, and C++, any numeric type
value can be assigned to any numeric type
variable
• In Java, only widening assignment
coercions are done
• In Ada, there is no assignment
coercion
Unit-2(PRINCIPLES OF
1-146
PROGRAMMING LANGUAGES)
Summary
• Expressions
• Operator precedence and associativity
• Operator overloading
• Mixed-type expressions
• Various forms of assignment

Unit-2(PRINCIPLES OF
1-147
PROGRAMMING LANGUAGES)
Statement
s
• Introduction
• Selection Statements
• Iterative Statements
• Unconditional Branching
• Guarded Commands
• Conclusions

Unit-2(PRINCIPLES OF
1-148
PROGRAMMING LANGUAGES)
Levels of Control Flow
– Within expressions
– Among program units
– Among program statements

Unit-2(PRINCIPLES OF
1-149
PROGRAMMING LANGUAGES)
Control Statements: Evolution
• FORTRAN I control statements were based
directly on IBM 704 hardware
• Much research and argument in the 1960s
about the issue
– One important result: It was proven that all
algorithms represented by flowcharts can be
coded with only two-way selection and pretest
logical loops

Unit-2(PRINCIPLES OF
1-150
PROGRAMMING LANGUAGES)
Control Structure
• A control structure is a control statement and
the statements whose execution it controls
• Design question
– Should a control structure have multiple entries?

Unit-2(PRINCIPLES OF
1-151
PROGRAMMING LANGUAGES)
Selection Statements
• A selection statement provides the means of
choosing between two or more paths of
execution
• Two general categories:
– Two-way selectors
– Multiple-way selectors

Unit-2(PRINCIPLES OF
1-152
PROGRAMMING LANGUAGES)
Two-Way Selection Statements
• General form:
if control_expression
then clause
else clause
• Design Issues:
– What is the form and type of the control
expression?
– How are the then and else clauses
specified?
– How should the meaning of nested selectors be
specified?
Unit-2(PRINCIPLES OF
1-153
PROGRAMMING LANGUAGES)
The Control Expression
• If the then reserved word or some other
syntactic marker is not used to introduce the
then clause, the control expression is placed in
parentheses
• In C89, C99, Python, and C++, the control
expression can be arithmetic
• In languages such as Ada, Java, Ruby, and C#,
the control expression must be Boolean

Unit-2(PRINCIPLES OF
1-154
PROGRAMMING LANGUAGES)
Clause Form
• In many contemporary languages, the then and else clauses
can be single statements or compound statements
• In Perl, all clauses must be delimited by braces (they must
be
compound)
• In Fortran 95, Ada, and Ruby, clauses are statement
sequences
• Python uses indentation to define clauses
if x > y :
x = y
print

"case 1" Unit-2(PRINCIPLES OF


1-155
PROGRAMMING LANGUAGES)
Nesting Selectors
• Java example
if (sum == 0)
if (count == 0)
result =
0;
else result = 1;
• Which if gets the
else?
• Java's static semantics rule: else
matches with the nearest if
Unit-2(PRINCIPLES OF
1-156
PROGRAMMING LANGUAGES)
Nesting Selectors (continued)
• To force an alternative semantics, compound
statements may be used:
if (sum == 0)
{ if (count ==
0)
result = 0;
}
else result = 1;
• The above solution is used in
C, C++, and C#
• Perl requires that all then and
Unit-2(PRINCIPLES OF
1-157
else clauses to be compound
PROGRAMMING LANGUAGES)
Nesting Selectors (continued)
• Statement sequences as clauses: Ruby
if sum == 0 then
if count == 0 then
result = 0
else
result = 1
end
end

Unit-2(PRINCIPLES OF
1-158
PROGRAMMING LANGUAGES)
Nesting Selectors (continued)
• Python
if sum == 0 :
if count == 0 :
result = 0
else :
result = 1

Unit-2(PRINCIPLES OF
1-159
PROGRAMMING LANGUAGES)
Multiple-Way Selection Statements
• Allow the selection of one of any number of statements or
statement groups
• Design Issues:
1. What is the form and type of the control expression?
2. How are the selectable segments specified?
3. Is execution flow through the structure restricted to include just a
single selectable segment?
4. How are case values specified?
5. What is done about unrepresented expression values?

Unit-2(PRINCIPLES OF
1-160
PROGRAMMING LANGUAGES)
Multiple-Way Selection: Examples
• C, C++, and Java
switch (expression) {
case const_expr_1: stmt_1;

case const_expr_n: stmt_n;
[default: stmt_n+1]
}

Unit-2(PRINCIPLES OF
1-161
PROGRAMMING LANGUAGES)
Multiple-Way Selection: Examples
• Design choices for C’s switch statement
1. Control expression can be only an integer type
2. Selectable segments can be statement sequences, blocks, or
compound statements
3. Any number of segments can be executed in one execution of
the construct (there is no implicit branch at the end of
selectable segments)
4. default clause is for unrepresented values (if there is no
default, the whole statement does nothing)

Unit-2(PRINCIPLES OF
1-162
PROGRAMMING LANGUAGES)
Multiple-Way Selection: Examples
• C#
– Differs from C in that it has a static semantics rule
that disallows the implicit execution of more than
one segment

– Each selectable segment must end with an


unconditional branch (goto or break)

– Also, in C# the control expression and the case


constants can be strings
Unit-2(PRINCIPLES OF
1-163
PROGRAMMING LANGUAGES)
Multiple-Way Selection: Examples
• Ada
case expression is
when choice list => stmt_sequence;

when choice list => stmt_sequence;
when others => stmt_sequence;]
end case;

• More reliable than C’s switch (once a


stmt_sequence execution is completed, control is
passed to the first statement after the case
statement
Unit-2(PRINCIPLES OF
1-164
PROGRAMMING LANGUAGES)
Multiple-Way Selection: Examples
• Ada design choices:
1. Expression can be any ordinal type
2. Segments can be single or compound
[Link] one segment can be executed per execution of the
construct
4. Unrepresented values are not allowed
• Constant List Forms:
1. A list of constants
2. Can include:
- Subranges
- Boolean OR operators (|)

Unit-2(PRINCIPLES OF
1-165
PROGRAMMING LANGUAGES)
Multiple-Way Selection: Examples
• Ruby has two forms of case statements
1. One form uses when conditions
leap = case
when year % 400 == 0 then true
when year % 100 == 0 then false
else year % 4 == 0
end
2. The other uses a case value and when values
case in_val
when -1 then neg_count++
when 0 then zero_count+
+ when 1 then
pos_count++
else puts "Error – in_val is out of range"
end Unit-2(PRINCIPLES OF
1-166
PROGRAMMING LANGUAGES)
Multiple-Way Selection Using if
• Multiple Selectors can appear as direct
extensions to two-way selectors, using else-if
clauses, for example in Python:
if count < 10 :
bag1 = True
elif count < 100 :
bag2 = True
elif count < 1000 :
bag3 = True
Unit-2(PRINCIPLES OF
1-167
PROGRAMMING LANGUAGES)
Multiple-Way Selection Using if
• The Python example can be written as a Ruby
case
case
when count < 10 then bag1 = true
when count < 100 then bag2 = true
when count < 1000 then bag3 = true
end

Unit-2(PRINCIPLES OF
1-168
PROGRAMMING LANGUAGES)
Iterative Statements
• The repeated execution of a statement or
compound statement is accomplished either
by iteration or recursion
• General design issues for iteration control
statements:
1. How is iteration controlled?
2. Where is the control mechanism in the
loop?

Unit-2(PRINCIPLES OF
1-169
PROGRAMMING LANGUAGES)
Counter-Controlled Loops
• A counting iterative statement has a loop
variable, and a means of specifying the initial
and terminal, and stepsize values
• Design Issues:
1. What are the type and scope of the loop
variable?
2. Should it be legal for the loop variable or loop
parameters to be changed in the loop body, and if
so, does the change affect loop control?
3. Should the loop parameters be evaluated only once,
or once for every iteration?

Unit-2(PRINCIPLES OF
1-170
PROGRAMMING LANGUAGES)
Iterative Statements: Examples
• FORTRAN 95 syntax
DO label var = start, finish [, stepsize]
• Stepsize can be any value but zero
• Parameters can be expressions
• Design choices:
1. Loop variable must be INTEGER
2. The loop variable cannot be changed in the loop, but the
parameters can; because they are evaluated only once, it does not
affect loop control
3. Loop parameters are evaluated only once

Unit-2(PRINCIPLES OF
1-171
PROGRAMMING LANGUAGES)
Iterative Statements: Examples
• FORTRAN 95 : a second form:
[name:] Do variable = initial, terminal [,stepsize]

End Do [name]

- Cannot branch into either of Fortran’s Do statements

Unit-2(PRINCIPLES OF
1-172
PROGRAMMING LANGUAGES)
Iterative Statements: Examples
• Ada
for var in [reverse] discrete_range loop
...
end loop
• Design choices:
- Type of the loop variable is that of the discrete range (A
discrete range is a sub-range of an integer or enumeration
type).
- Loop variable does not exist outside the loop
- The loop variable cannot be changed in the loop, but the
discrete range can; it does not affect loop control
- The discrete range is evaluated just once
• Cannot branch into the loop body

Unit-2(PRINCIPLES OF
1-173
PROGRAMMING LANGUAGES)
Iterative Statements: Examples
• C-based languages
for ([expr_1] ; [expr_2] ; [expr_3]) statement
- The expressions can be whole statements, or even statement sequences,
with the statements separated by commas
– The value of a multiple-statement expression is the value of the last statement
in the expression
– If the second expression is absent, it is an infinite loop
• Design choices:
- There is no explicit loop variable
- Everything can be changed in the loop
- The first expression is evaluated once, but the other two are evaluated
with each iteration

Unit-2(PRINCIPLES OF
1-174
PROGRAMMING LANGUAGES)
Iterative Statements: Examples
• C++ differs from C in two ways:
1. The control expression can also be Boolean
2. The initial expression can include variable
definitions (scope is from the definition to the
end of the loop body)
• Java and C#
– Differs from C++ in that the control expression
must be Boolean

Unit-2(PRINCIPLES OF
1-175
PROGRAMMING LANGUAGES)
Iterative Statements: Examples
• Python
for loop_variable in object:
- loop body
[else:
- else clause]

– The object is often a range, which is either a list of values in


brackets ([2, 4, 6]), or a call to the range function (range(5), which
returns 0, 1, 2, 3, 4

– The loop variable takes on the values specified in the given


range, one for each iteration

– The else clause, which is optional, is executed if the loop terminates


normally

Unit-2(PRINCIPLES OF
1-176
PROGRAMMING LANGUAGES)
Iterative Statements: Logically-
Controlled Loops
• Repetition control is based on a Boolean
expression
• Design issues:
– Pretest or posttest?
– Should the logically controlled loop be a special
case of the counting loop statement or
a separate statement?

Unit-2(PRINCIPLES OF
1-177
PROGRAMMING LANGUAGES)
Iterative Statements: Logically-Controlled
Loops: Examples
• C and C++ have both pretest and posttest
forms, in which the control expression can be
arithmetic:
while (ctrl_expr) do
loop body loop body
while (ctrl_expr)
• Java is like C and C++, except the control
expression must be Boolean (and the body can
only be entered at the beginning -- Java has
no goto
Unit-2(PRINCIPLES OF
1-178
PROGRAMMING LANGUAGES)
Iterative Statements: Logically-Controlled Loops
Examples

• Ada has a pretest version, but no posttest

• FORTRAN 95 has neither

• Perl and Ruby have two pretest logical loops,


while and until. Perl also has two
posttest loops

Unit-2(PRINCIPLES OF
1-179
PROGRAMMING LANGUAGES)
Iterative Statements: User-Located Loop Control
Mechanisms

• Sometimes it is convenient for the


programmers to decide a location for loop
control (other than top or bottom of the
loop)
• Simple design for single loops (e.g., break)
• Design issues for nested loops
1. Should the conditional be part of the exit?
2. Should control be transferable out of more than
one loop?

Unit-2(PRINCIPLES OF
1-180
PROGRAMMING LANGUAGES)
Iterative Statements: User-Located Loop Control
Mechanisms break and continue

• C , C++, Python, Ruby, and C# have unconditional


unlabeled exits (break)
• Java and Perl have unconditional labeled exits
(break in Java, last in Perl)
• C, C++, and Python have an unlabeled control
statement, continue, that skips the remainder of
the current iteration, but does not exit the loop
• Java and Perl have labeled versions of continue

Unit-2(PRINCIPLES OF
1-181
PROGRAMMING LANGUAGES)
Iterative Statements: Iteration Based on Data
Structures
• Number of elements of in a data structure
control loop iteration
• Control mechanism is a call to an iterator
function that returns the next element in some
chosen order, if there is one; else loop is
terminate
• C's for can be used to build a user-
defined iterator:
for (p=root; p==NULL;
traverse(p)){
}

Unit-2(PRINCIPLES OF
1-182
PROGRAMMING LANGUAGES)
Iterative Statements: Iteration Based on Data
Structures (continued)
PHP
- current points at one element of the array
- next moves current to the next element
- reset moves current to the first element

• Java
- For any collection that implements the Iterator
interface
- next moves the pointer into the collection
- hasNext is a predicate
- remove deletes an element

• Perl has a built-in iterator for arrays and hashes


Unit-2(PRINCIPLES OF
1-183
PROGRAMMING LANGUAGES)
Iterative Statements: Iteration Based on
Data Structures (continued)
• Java 5.0 (uses for, although it is called foreach)
- For arrays and any other class that implements
Iterable interface, e.g., ArrayList

for (String myElement : myList) { … }

• C#’s foreach statement iterates on the elements of arrays


and
other collections:
Strings[] = strList = {"Bob", "Carol", "Ted"};
foreach (Strings name in strList)
[Link] ("Name: {0}", name);

- The notation {0} indicatesPROGRAMMING


Unit-2(PRINCIPLES OF
the positionLANGUAGES)
in the string to be 1-184
Iterative Statements: Iteration Based on
Data Structures (continued)

• Lua
– Lua has two forms of its iterative statement, one
like Fortran’s Do, and a more general form:
for variable_1 [, variable_2] in iterator(table) do

end
– The
mos
t
com Unit-2(PRINCIPLES OF
1-185
mo PROGRAMMING LANGUAGES)
Unconditional Branching
• Transfers execution control to a specified place in the program
• Represented one of the most heated debates in 1960’s and
1970’s
• Major concern: Readability
• Some languages do not support goto statement (e.g.,
Java)
• C# offers goto statement (can be used in switch
statements)
• Loop exit statements are restricted and somewhat
camouflaged goto’s

Unit-2(PRINCIPLES OF
1-186
PROGRAMMING LANGUAGES)
Guarded Commands
• Designed by Dijkstra
• Purpose: to support a new programming
methodology that supported
verification (correctness) during
development
• Basis for two linguistic mechanisms for
concurrent programming (in CSP and Ada)
• Basic Idea: if the order of evaluation is not
important, the program should not specify
one
Unit-2(PRINCIPLES OF
1-187
PROGRAMMING LANGUAGES)
Selection Guarded Command
• Form
if <Boolean exp> -> <statement>
[] <Boolean exp> -> <statement>
...
[] <Boolean exp> -> <statement>
fi
• Semantics: when construct is reached,
– Evaluate all Boolean expressions
– If more than one are true, choose one non-
deterministically
– If none are true, it is a runtime error

Unit-2(PRINCIPLES OF
1-188
PROGRAMMING LANGUAGES)
Loop Guarded Command
• Form
do <Boolean> -> <statement>
[] <Boolean> -> <statement>
...
[] <Boolean> -> <statement>
od
• Semantics: for each iteration
– Evaluate all Boolean expressions
– If more than one are true, choose one non-
deterministically; then start loop again
– If none are true,PROGRAMMING
U e x i LANGUAGES)
nit -
1-189
Guarded Commands: Rationale
• Connection between control statements and
program verification is intimate
• Verification is impossible with goto
statements
• Verification is possible with only selection and
logical pretest loops
• Verification is relatively simple with only
guarded commands

Unit-2(PRINCIPLES OF
1-190
PROGRAMMING LANGUAGES)
Summary
• The data types of a language are a large part of what
determines that language’s style and usefulness
• The primitive data types of most imperative
languages include
numeric, character, and Boolean types
• The user-defined enumeration and subrange types are
convenient and add to the readability and reliability of
programs
• Arrays and records are included in most languages
• Pointers are used for addressing flexibility and to control
dynamic storage management

Unit-2(PRINCIPLES OF
1-191
PROGRAMMING LANGUAGES)
Conclusion
• Variety of statement-level structures
• Choice of control statements beyond selection
and logical pretest loops is a trade-off
between language size and writability
• Functional and logic programming languages
are quite different control structures

Unit-2(PRINCIPLES OF
1-192
PROGRAMMING LANGUAGES)
UNIT-
3

351
CONCEPTS
• Introduction
• Fundamentals of Subprograms
• Design Issues for Subprograms
• Local Referencing Environments
• Parameter-Passing Methods
• Parameters That Are Subprograms
• Overloaded Subprograms
• Generic Subprograms
• Design Issues for Functions
• User-Defined Overloaded Operators
• Coroutines
Unit-3 (PRINCIPLES OF
1-194
PROGRAMMING LANGUAGE)
CONCEPTS
• The General Semantics of Calls and Returns
• Implementing “Simple” Subprograms
• Implementing Subprograms with Stack-Dynamic Local
Variables
• Nested Subprograms
• Blocks
• Implementing Dynamic Scoping

Unit-3 (PRINCIPLES OF
1-195
PROGRAMMING LANGUAGE)
Introduction
• Two fundamental abstraction facilities
– Process abstraction
• Emphasized from early days
– Data abstraction
• Emphasized in the1980s

Unit-3 (PRINCIPLES OF
1-196
PROGRAMMING LANGUAGE)
Fundamentals of Subprograms
• Each subprogram has a single entry point
• The calling program is suspended during
execution of the called subprogram
• Control always returns to the caller when the
called subprogram’s execution terminates

Unit-3 (PRINCIPLES OF
1-197
PROGRAMMING LANGUAGE)
Basic Definitions
• A subprogram definition describes the interface to and the actions of the
subprogram abstraction
- In Python, function definitions are executable; in
all other languages, they are non-executable
• A subprogram call is an explicit request that the subprogram be executed
• A subprogram header is the first part of the definition, including the name,
the kind of subprogram, and the formal parameters
• The parameter profile (aka signature) of a subprogram is the number,
order, and types of its parameters
• The protocol is a subprogram’s parameter profile and, if it is a function, its
return type

Unit-3 (PRINCIPLES OF
1-198
PROGRAMMING LANGUAGE)
Basic Definitions (continued)
• Function declarations in C and C++ are often called prototypes
• 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

Unit-3 (PRINCIPLES OF
1-199
PROGRAMMING LANGUAGE)
Actual/Formal Parameter
Correspondence
• Positional
– The binding of actual parameters to formal parameters is by position:
the first actual parameter is bound to the first formal parameter and
so forth
– Safe and effective
• Keyword
– The name of the formal parameter to which an actual parameter is to
be bound is specified with the actual parameter
– Advantage: Parameters can appear in any order, thereby avoiding
parameter correspondence errors
– Disadvantage: User must know the formal parameter’s names

Unit-3 (PRINCIPLES OF
1-200
PROGRAMMING LANGUAGE)
Formal Parameter Default Values
• In certain languages (e.g., C++, Python, Ruby, Ada, PHP), formal
parameters can have default values (if no actual parameter is passed)
– In C++, default parameters must appear last because parameters are
positionally associated

• Variable numbers of parameters


– C# methods can accept a variable number of parameters as long as they are of the same
type—the corresponding formal parameter is an array preceded by params
– In Ruby, the actual parameters are sent as elements of a hash literal and the
corresponding formal parameter is preceded by an asterisk.
– In Python, the actual is a list of values and the corresponding formal parameter is a
name with an asterisk
– In Lua, a variable number of parameters is represented as a formal parameter with three
periods; they are accessed with a for statement or with a multiple assignment from the
three periods

Unit-3 (PRINCIPLES OF
1-201
PROGRAMMING LANGUAGE)

Ruby Blocks
Ruby includes a number of iterator functions, which are
often used to process the elements of arrays
• Iterators are implemented with blocks, which can also be
defined by applications
• Blocks are attached methods calls; they can have
parameters (in vertical bars); they are executed when the
method executes a yield statement
def fibonacci(last)
first, second = 1, 1
while first <= last
yield first
first, second = second, first + second
end
end

puts "Fibonacci numbers less than 100


are:" fibonacci(100) {|num| print num, "
"}
puts

Unit-3 (PRINCIPLES OF
1-202
PROGRAMMING LANGUAGE)
Procedures and Functions
• There are two categories of subprograms
– Procedures are collection of statements that
define parameterized computations
– Functions structurally resemble procedures but
are semantically modeled on mathematical
functions
• They are expected to produce no side effects
• In practice, program functions have side effects

Unit-3 (PRINCIPLES OF
1-203
PROGRAMMING LANGUAGE)
Design Issues for Subprograms
• Are local variables static or dynamic?
• Can subprogram definitions appear in other subprogram
definitions?
• What parameter passing methods are provided?
• Are parameter types checked?
• If subprograms can be passed as parameters and subprograms
can be nested, what is the referencing environment of a
passed subprogram?
• Can subprograms be overloaded?
• Can subprogram be generic?

Unit-3 (PRINCIPLES OF
1-204
PROGRAMMING LANGUAGE)
Local Referencing Environments
• Local variables can be stack-dynamic
- Advantages
• Support for recursion
• Storage for locals is shared among some subprograms
– Disadvantages
• Allocation/de-allocation, initialization time
• Indirect addressing
• Subprograms cannot be history sensitive
• Local variables can be static
– Advantages and disadvantages are the opposite of those for stack-
dynamic local variables

Unit-3 (PRINCIPLES OF
1-205
PROGRAMMING LANGUAGE)
Semantic Models of Parameter Passing

• In mode
• Out mode
• Inout mode

Unit-3 (PRINCIPLES OF
1-206
PROGRAMMING LANGUAGE)
Models of Parameter Passing

Unit-3 (PRINCIPLES OF
1-207
PROGRAMMING LANGUAGE)
Conceptual Models of Transfer
• Physically move a path
• Move an access path

Unit-3 (PRINCIPLES OF
1-208
PROGRAMMING LANGUAGE)
Pass-by-Value (In Mode)
• The value of the actual parameter is used to initialize the
corresponding formal parameter
– Normally implemented by copying
– Can be implemented by transmitting an access path but not
recommended (enforcing write protection is not easy)
– Disadvantages (if by physical move): additional storage is required
(stored twice) and the actual move can be costly (for large
parameters)
– Disadvantages (if by access path method): must write-protect in the
called subprogram and accesses cost more (indirect addressing)

Unit-3 (PRINCIPLES OF
1-209
PROGRAMMING LANGUAGE)
Pass-by-Result (Out Mode)
• When a parameter is passed by result, no
value is transmitted to the subprogram; the
corresponding formal parameter acts as a
local variable; its value is transmitted to
caller’s actual parameter when control is
returned to the caller, by physical move
– Require extra storage location and copy
operation
• Potential problem: sub(p1, p1);
whichever formal parameter is copied back
will represent the current value of p1
Unit-3 (PRINCIPLES OF
1-210
PROGRAMMING LANGUAGE)
Pass-by-Value-Result (inout Mode)
• A combination of pass-by-value and pass-by-
result
• Sometimes called pass-by-copy
• Formal parameters have local storage
• Disadvantages:
– Those of pass-by-result
– Those of pass-by-value

Unit-3 (PRINCIPLES OF
1-211
PROGRAMMING LANGUAGE)
Pass-by-Reference (Inout Mode)
• Pass an access path
• Also called pass-by-sharing
• Advantage: Passing process is efficient (no
copying and no duplicated storage)
• Disadvantages
– Slower accesses (compared to pass-by-value) to
formal parameters
– Potentials for unwanted side effects (collisions)
– Unwanted aliases (access broadened)

Unit-3 (PRINCIPLES OF
1-212
PROGRAMMING LANGUAGE)
Pass-by-Name (Inout 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 or assignment
• Allows flexibility in late binding

Unit-3 (PRINCIPLES OF
1-213
PROGRAMMING LANGUAGE)
Implementing Parameter-Passing Methods

• In most language parameter communication


takes place thru the run-time stack
• Pass-by-reference are the simplest to
implement; only an address is placed in the
stack
• A subtle but fatal error can occur with pass-
by-reference and pass-by-value-result: a
formal parameter corresponding to a constant
can mistakenly be changed

Unit-3 (PRINCIPLES OF
1-214
PROGRAMMING LANGUAGE)
Parameter Passing Methods of Major Languages
• C
– Pass-by-value
– Pass-by-reference is achieved by using pointers as
parameters
• C++
– A special pointer type called reference type for
pass-by-reference
• Java
– All parameters are passed are passed by value
– Object parameters are passed by reference
• Ada
– Three semantics modes of parameter
transmission: in, out, in out; in is the
default mode
– Formal parameters declared out can be
but not referenced;
assigned those
PROGRAMMING declared in can
Unit-3 (PRINCIPLES OF
LANGUAGE)
1-373
Parameter Passing Methods of Major Languages
(continued)
• Fortran 95
- Parameters can be declared to be in, out, or inout mode
• C#
- Default method: pass-by-value
– Pass-by-reference is specified by preceding both a formal parameter
and its actual parameter with ref
• PHP: very similar to C#
• Perl: all actual parameters are implicitly placed in a
predefined array named @_
• Python and Ruby use pass-by-assignment (all data values are
objects)

Unit-3 (PRINCIPLES OF
1-216
PROGRAMMING LANGUAGE)
Type Checking Parameters
• Considered very important for reliability
• FORTRAN 77 and original C: none
• Pascal, FORTRAN 90, Java, and Ada: it is always required
• ANSI C and C++: choice is made by the user
– Prototypes
• Relatively new languages Perl, JavaScript, and PHP do not
require type checking
• In Python and Ruby, variables do not have types (objects do),
so parameter type checking is not possible

Unit-3 (PRINCIPLES OF
1-217
PROGRAMMING LANGUAGE)
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

Unit-3 (PRINCIPLES OF
1-218
PROGRAMMING LANGUAGE)
Multidimensional Arrays as Parameters: C and
C++
• Programmer is required to include the
declared sizes of all but the first subscript in
the actual parameter
• 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 in terms of the size parameters

Unit-3 (PRINCIPLES OF
1-219
PROGRAMMING LANGUAGE)
Multidimensional Arrays as Parameters: Ada

• Ada – not a problem


– Constrained arrays – size is part of the array’s
type
– Unconstrained arrays - declared size is part of the
object declaration

Unit-3 (PRINCIPLES OF
1-220
PROGRAMMING LANGUAGE)
Multidimensional Arrays as Parameters: Fortran

• Formal parameter that are arrays have a


declaration after the header
– For single-dimension arrays, the subscript is
irrelevant
– For multidimensional arrays, the sizes are sent as
parameters and used in the declaration of the
formal parameter, so those variables are used in
the storage mapping function

Unit-3 (PRINCIPLES OF
1-221
PROGRAMMING LANGUAGE)
Multidimensional Arrays as Parameters: Java
and C#

• Similar to Ada
• Arrays are objects; they are all single-
dimensioned, but the elements can be arrays
• Each array inherits a named constant
(length in Java, Length in C#) that is set
to the length of the array when the array
object is created

Unit-3 (PRINCIPLES OF
1-222
PROGRAMMING LANGUAGE)
Design Considerations for Parameter Passing

• Two important considerations


– Efficiency
– One-way or two-way data transfer
• But the above considerations are in conflict
– Good programming suggest limited access to
variables, which means one-way whenever
possible
– But pass-by-reference is more efficient to pass
structures of significant size
Unit-3 (PRINCIPLES OF
1-223
PROGRAMMING LANGUAGE)
Parameters that are Subprogram
Names
• It is sometimes convenient to pass
subprogram names as parameters
• Issues:
1. Are parameter types checked?
2. What is the correct referencing environment for
a subprogram that was sent as a parameter?

Unit-3 (PRINCIPLES OF
1-224
PROGRAMMING LANGUAGE)
Parameters that are Subprogram Names:
Parameter Type Checking
• C and C++: functions cannot be passed as parameters but
pointers to functions can be passed and their types include
the types of the parameters, so parameters can be type
checked
• FORTRAN 95 type checks
• Ada does not allow subprogram parameters; an alternative
is provided via Ada’s generic facility
• Java does not allow method names to be passed as
parameters

Unit-3 (PRINCIPLES OF
1-225
PROGRAMMING LANGUAGE)
Parameters that are Subprogram
Names: Referencing Environment
• Shallow binding: The environment of the call
statement that enacts the passed subprogram
- Most natural for dynamic-scoped
languages
• Deep binding: The environment of the
definition of the passed subprogram
- Most natural for static-scoped
languages
• Ad hoc binding: The environment of the call
statement that passed the subprogram
Unit-3 (PRINCIPLES OF
1-226
PROGRAMMING LANGUAGE)
Overloaded Subprograms
• An overloaded subprogram is one that has the same name as
another subprogram in the same referencing environment
– Every version of an overloaded subprogram has a unique protocol
• C++, Java, C#, and Ada include predefined overloaded
subprograms
• In Ada, the return type of an overloaded function can be used
to disambiguate calls (thus two overloaded functions can have
the same parameters)
• Ada, Java, C++, and C# allow users to write multiple versions
of subprograms with the same name

Unit-3 (PRINCIPLES OF
1-227
PROGRAMMING LANGUAGE)
Generic Subprograms
• A generic or polymorphic subprogram 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
the subprogram provides parametric polymorphism
- A cheap compile-time substitute for dynamic binding

Unit-3 (PRINCIPLES OF
1-228
PROGRAMMING LANGUAGE)
Generic Subprograms (continued)
• Ada
– Versions of a generic subprogram are created by
the compiler when explicitly instantiated by a
declaration statement
– Generic subprograms are preceded by a generic
clause that lists the generic variables, which
can be types or other subprograms

Unit-3 (PRINCIPLES OF
1-229
PROGRAMMING LANGUAGE)
Generic Subprograms (continued)
• C++
– Versions of a generic subprogram are created
implicitly when the subprogram is named in a call
or when its address is taken with the & operator
– Generic subprograms are preceded by a template
clause that lists the generic variables, which can
be type names or class names

Unit-3 (PRINCIPLES OF
1-230
PROGRAMMING LANGUAGE)
Generic Subprograms (continued)
• Java 5.0
- Differences between generics in Java 5.0 and those of C++
and Ada:
1. Generic parameters in Java 5.0 must be classes
[Link] 5.0 generic methods are instantiated just once as truly
generic methods
[Link] can be specified on the range of classes that
can be passed to the generic method as generic parameters
4. Wildcard types of generic parameters

Unit-3 (PRINCIPLES OF
1-231
PROGRAMMING LANGUAGE)
Generic Subprograms (continued)
• C# 2005
- Supports generic methods that are similar to
those of Java 5.0
- One difference: actual type parameters in a
call can be omitted if the compiler can infer
the unspecified type

Unit-3 (PRINCIPLES OF
1-232
PROGRAMMING LANGUAGE)
Examples of parametric
polymorphism: C++
template <class Type>
Type max(Type first, Type second) {
return first > second ? first : second;
}

• The above template can be instantiated for any type for which
operator > is defined

int max (int first, int second)


{ return first > second? first :
second;
}
Unit-3 (PRINCIPLES OF
1-233
PROGRAMMING LANGUAGE)
Design Issues for Functions
• Are side effects allowed?
– Parameters should always be in-mode to reduce side effect (like
Ada)
• What types of return values are allowed?
– Most imperative languages restrict the return types
– C allows any type except arrays and functions
– C++ is like C but also allows user-defined types
– Ada subprograms can return any type (but Ada subprograms are not
types, so they cannot be returned)
– Java and C# methods can return any type (but because methods are
not types, they cannot be returned)
– Python and Ruby treat methods as first-class objects, so they can be
returned, as well as any other class
– Lua allows functions to return multiple values
Unit-3 (PRINCIPLES OF
1-234
PROGRAMMING LANGUAGE)
User-Defined Overloaded
Operators
• Operators can be overloaded in Ada, C++,
Python, and Ruby
• An Ada example
function "*" (A,B: in Vec_Type): return
Integer
is
Sum: Integer := 0;
begin
for Index in A'range loop
Sum := Sum + A(Index) * B(Index)
end loop
return sum;
end "*";

c = a * b;
-- a, b, and
c are of
Unit-3 (PRINCIPLES OF
type PROGRAMMING LANGUAGE)
1-235
Coroutines
• A coroutine is a subprogram that has multiple entries and
controls them itself – supported directly in Lua
• Also called symmetric control: caller and called
coroutines are
on a more equal basis
• 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
executed statement in the coroutine
• Coroutines repeatedly resume each other, possibly
forever
• Coroutines provide quasi-concurrent execution of program
units (the coroutines); their execution is interleaved, but not
overlapped Unit-3 (PRINCIPLES OF
1-236
PROGRAMMING LANGUAGE)
Coroutines Illustrated: Possible Execution
Controls

Unit-3 (PRINCIPLES OF
1-237
PROGRAMMING LANGUAGE)
Coroutines Illustrated: Possible Execution
Controls

Unit-3 (PRINCIPLES OF
1-238
PROGRAMMING LANGUAGE)
Coroutines Illustrated: Possible Execution
Controls with Loops

Unit-3 (PRINCIPLES OF
1-239
PROGRAMMING LANGUAGE)
The General Semantics of Calls and
Returns
• The subprogram call and return operations of
a language are together called its subprogram
linkage
• General semantics of subprogram calls
– Parameter passing methods
– Stack-dynamic allocation of local variables
– Save the execution status of calling program
– Transfer of control and arrange for the return
– If subprogram nesting is supported, access to
nonlocal variables must be arranged

Unit-3 (PRINCIPLES OF
1-240
PROGRAMMING LANGUAGE)
The General Semantics of Calls and Returns

• General semantics of subprogram returns:

– In mode and inout mode parameters must have


their values returned
– Deallocation of stack-dynamic locals
– Restore the execution status
– Return control to the caller

Unit-3 (PRINCIPLES OF
1-241
PROGRAMMING LANGUAGE)
Implementing “Simple” Subprograms:
Call Semantics
• Call Semantics:

- Save the execution status of the caller


- Pass the parameters
- Pass the return address to the callee
- Transfer control to the callee

Unit-3 (PRINCIPLES OF
1-242
PROGRAMMING LANGUAGE)
Implementing “Simple” Subprograms:
Return Semantics
• Return Semantics:
– If pass-by-value-result or out mode parameters
are used, move the current values of those
parameters to their corresponding actual
parameters
– If it is a function, move the functional value to a
place the caller can get it
– Restore the execution status of the caller
– Transfer control back to the caller
• Required storage:
– Status information, parameters, return address,
return value for functions

Unit-3 (PRINCIPLES OF
1-243
PROGRAMMING LANGUAGE)
Implementing “Simple” Subprograms:
Parts
• Two separate parts: the actual code and the non-
code part (local variables and data that can
change)
• The format, or layout, of the non-code part of an
executing subprogram is called an activation
record
• An activation record instance is a concrete
example of an activation record (the collection of
data for a particular subprogram activation)

Unit-3 (PRINCIPLES OF
1-244
PROGRAMMING LANGUAGE)
An Activation Record for “Simple”
Subprograms

Unit-3 (PRINCIPLES OF
1-245
PROGRAMMING LANGUAGE)
Code and Activation Records of a Pr ogram with
“Simple” Subprograms

Unit-3 (PRINCIPLES OF
1-246
PROGRAMMING LANGUAGE)
Implementing Subprograms with
Stack-Dynamic Local Variables
• More complex activation record
– The compiler must generate code to cause
implicit allocation and deallocation of local
variables
– Recursion must be supported (adds the possibility
of multiple simultaneous activations of a
subprogram)

Unit-3 (PRINCIPLES OF
1-247
PROGRAMMING LANGUAGE)
Typical Activation Record for a Language with
Stack-Dynamic Local Variables

Unit-3 (PRINCIPLES OF
1-248
PROGRAMMING LANGUAGE)
Implementing Subprograms with Stack-Dynamic Local
Variables: Activation Record
• The activation record format is static, but its size may be
dynamic
• The dynamic link points to the top of an instance of the
activation record of the caller
• An activation record instance is dynamically created when a
subprogram is called
• Activation record instances reside on the run-time stack
• The Environment Pointer (EP) must be maintained by the run-
time system. It always points at the base of the activation
record instance of the currently executing program unit

Unit-3 (PRINCIPLES OF
1-249
PROGRAMMING LANGUAGE)
An Example: C Function
void sub(float total, int part)
{ [4]

int list[5]; [3]

float sum; [2]

… [1]

} [0]

Unit-3 (PRINCIPLES OF
1-250
PROGRAMMING LANGUAGE)
An Example Without Recursion
void A(int x) {
int y;
...
C(y);
...
}
void B(float r) {
int s, t;
...
A(s);
main calls B
... B calls A
}
void C(int q) { A calls C
...
}
void main() {
float p;
...
B(p);
...
}

Unit-3 (PRINCIPLES OF
1-251
PROGRAMMING LANGUAGE)
An Example Without Recursion

Unit-3 (PRINCIPLES OF
1-252
PROGRAMMING LANGUAGE)
Dynamic Chain and Local Offset
• 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, whose address is in the EP.
This offset is called the local_offset
• The local_offset of a local variable can be determined by the
compiler at compile time

Unit-3 (PRINCIPLES OF
1-253
PROGRAMMING LANGUAGE)
An Example With Recursion
• 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
} Unit-3 (PRINCIPLES OF
1-254
PROGRAMMING LANGUAGE)
Activation Record for factorial

Unit-3 (PRINCIPLES OF
1-255
PROGRAMMING LANGUAGE)
Nested Subprograms
• Some non-C-based static-scoped languages (e.g., Fortran
95, Ada, Python, JavaScript, Ruby, and Lua) use stack-
dynamic local variables and allow subprograms to be nested
• All variables that can be non-locally accessed reside in some
activation record instance in the stack
• The process of locating a non-local reference:
1. Find the correct activation record instance
2. Determine the correct offset within that activation record instance

Unit-3 (PRINCIPLES OF
1-256
PROGRAMMING LANGUAGE)
Locating a Non-local Reference
• Finding the offset is easy
• Finding the correct activation record instance
– Static semantic rules guarantee that all non-local
variables that can be referenced have been
allocated in some activation record instance that
is on the stack when the reference is made

Unit-3 (PRINCIPLES OF
1-257
PROGRAMMING LANGUAGE)
Static Scoping
• 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

• Static_depth is an integer associated with a static scope


whose value is the depth of nesting of that scope

Unit-3 (PRINCIPLES OF
1-258
PROGRAMMING LANGUAGE)
Static Scoping (continued)
• 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 when it is declared

• A reference to a variable can be represented by the pair:


(chain_offset, local_offset),
where local_offset is the offset in the activation
record of the variable being referenced

Unit-3 (PRINCIPLES OF
1-259
PROGRAMMING LANGUAGE)
Example Ada Program
procedure Main_2 is
X : Integer;
procedure Bigsub is
A, B, C : Integer;
procedure Sub1 is
A, D : Integer;
begin -- of Sub1
A := B + C; <
1
end; -- of Sub1
procedure Sub2(X :
Integer) is
B, E : Integer;
procedure Sub3 is
C, E : Integer;
begin -- of Sub3
Sub1;
E := B + A:
<
2
end; -- of Sub3
begin -- of Sub2
Sub3;
A := D + E;
<
3
end; -- of Sub2 } Unit-3 (PRINCIPLES OF
begin -- of Bigsub PROGRAMMING LANGUAGE) 1-260
Sub2(7);
Example Ada Program (continued)

• Call sequence for Main_2

Main_2 calls
Bigsub Bigsub
calls Sub2 Sub2
calls Sub3 Sub3
calls Sub1

Unit-3 (PRINCIPLES OF
1-261
PROGRAMMING LANGUAGE)
Stack Contents at
Position 1

Unit-3 (PRINCIPLES OF
1-262
PROGRAMMING LANGUAGE)
Static Chain Maintenance
• At the call,
- 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
- Two methods:
1. Search the dynamic chain
2. Treat subprogram calls and
definitions like variable references
and definitions

Unit-3 (PRINCIPLES OF
1-263
PROGRAMMING LANGUAGE)
Evaluation of Static Chains
• Problems:
1. A nonlocal areference is slow
if the nesting depth is large
2. Time-critical code is difficult:
a. Costs of nonlocal references are
difficult to determine
b. Code changes can change the
nesting depth, and therefore the
cost
Unit-3 (PRINCIPLES OF
1-264
PROGRAMMING LANGUAGE)
Displays
• An alternative to static chains that solves the
problems with that approach
• Static links are stored in a single array called a
display
• The contents of the display at any given time
is a list of addresses of the accessible
activation record instances

Unit-3 (PRINCIPLES OF
1-265
PROGRAMMING LANGUAGE)
Blocks
• Blocks are user-specified local scopes for variables
• An example in C
{int temp;
temp = list [upper];
list [upper] = list [lower];
list [lower] = temp
}
• The lifetime of temp in the above example begins
when control enters the block
• An advantage of using a local variable like temp is that it
cannot interfere with any other variable with the same name

Unit-3 (PRINCIPLES OF
1-266
PROGRAMMING LANGUAGE)
Implementing Blocks
• Two Methods:
1. Treat blocks as parameter-less subprograms that
are always called from the same location
– Every block has an activation record; an instance is
created every time the block is executed
2. Since the maximum storage required for a block
can be statically determined, this amount of
space can be allocated after the local variables in
the activation record

Unit-3 (PRINCIPLES OF
1-267
PROGRAMMING LANGUAGE)
Implementing Dynamic Scoping
• Deep Access: non-local references are found
by searching the activation record instances
on the dynamic chain
- Length of the chain cannot be statically
determined
- Every activation record instance must
have variable names
• Shallow Access: put locals in a
central place
– One stack for each variable
name
Unit-3 (PRINCIPLES OF
– Central table with an entry
PROGRAMMING for
LANGUAGE)
1-268
Using Shallow Access to
Implement Dynamic Scoping
void sub3() {
int x, z;
x = u + v;

}
void sub2() {
int w, x;

}
void sub1() {
int v, w;

}
void main() {
int v, u;

}

Unit-3 (PRINCIPLES OF
1-269
PROGRAMMING LANGUAGE)
Summary
• A subprogram definition describes the actions represented by
the subprogram
• Subprograms can be either functions or procedures
• Local variables in subprograms can be stack-dynamic or static
• Three models of parameter passing: in mode, out mode, and
inout mode
• Some languages allow operator overloading
• Subprograms can be generic
• A coroutine is a special subprogram with multiple entries

Unit-3 (PRINCIPLES OF
1-270
PROGRAMMING LANGUAGE)
Summary
• Subprogram linkage semantics requires many
action by the implementation
• Simple subprograms have relatively basic
actions
• Stack-dynamic languages are more
complex
• Subprograms with stack-dynamic local
variables and nested subprograms have two
components
– actual code
– activation record Unit-3 (PRINCIPLES OF
PROGRAMMING LANGUAGE)
1-271
Summary
• Activation record instances contain formal
parameters and local variables among other
things
• Static chains are the primary method of
implementing accesses to non-local variables
in static-scoped languages with nested
subprograms
• Access to non-local variables in dynamic-
scoped languages can be implemented by use
of the dynamic chain or thru some central
variable table method

Unit-3 (PRINCIPLES OF
1-272
PROGRAMMING LANGUAGE)
UNIT-4
CONCEPTS
• Abstract Data types
• Concurrency
• Exception Handling
• Logic Programming Language

Unit-4(PRINCIPLES OF PROGRAMMING 274


LANGUAGE)
CONCEPTS
Introduction to logic programming language
A Brief Introduction to Predicate Calculus
Predicate Calculus and Proving Theorems
An Overview of Logic Programming
The Origins of Prolog
The Basic Elements of Prolog
Deficiencies of Prolog
Applications of Logic
Programming Unit-4(PRINCIPLES OF PROGRAMMING 275
LANGUAGE)
Abstract Data types

➢ An abstraction is a view or representation of an entity that


includes only the most significant attributes.
➢ The concept of abstraction is fundamental in programming
(and computer science).
➢ Nearly all programming languages support process
abstraction with subprograms.
➢ Nearly all programming languages designed since 1980
support data abstraction.

Unit-4(PRINCIPLES OF PROGRAMMING 276


LANGUAGE)
Introduction to Data Abstraction
An abstract data type is a user-defined data type that satisfies
the following two conditions:
–The representation of, and operations on, objects of the type
are defined in a single syntactic unit.
–The representation of objects of the type is hidden from the
program units that use these objects, so the only operations
possible are those provided in the type's definition.

Unit-4(PRINCIPLES OF PROGRAMMING 277


LANGUAGE)
Encapsulation
Original motivation :
Large programs have two special needs:
[Link] means of organization, other than simply division into
subprograms.
2. Some means of partial compilation (compilation units that are
smaller than the whole program).
Obvious solution : a grouping of subprograms that are
logically related into a unit that can be separately compiled.
These are called encapsulations.

Unit-4(PRINCIPLES OF PROGRAMMING 278


LANGUAGE)
Examples of Encapsulation
Mechanisms
1. Nested subprograms in some ALGOL-like
languages (e.g., Pascal).
2. FORTRAN 77 and C - Files containing one or
more subprograms can be independently
compiled.
3. FORTRAN 90, C++, Ada (and other
contemporary languages) - separately
compilable modules.

Unit-4(PRINCIPLES OF PROGRAMMING 279


LANGUAGE)
Language Requirements for
Data Abstraction
1. A syntactic unit in which to encapsulate the type definition.
2. A method of making type names and subprogram headers
visible to clients, while hiding actual definitions.
3. Some primitive operations must be built into the language
processor (usually just assignment and comparisons for
equality and inequality).
- Some operations are commonly needed, but must be defined
by the type designer.
- e.g., iterators, constructors, destructors.

Unit-4(PRINCIPLES OF PROGRAMMING 280


LANGUAGE)
Language Design Issues
1. Encapsulate a single type, or
something more?
2. What types can be abstract?
3. Can abstract types be parameterized?
4. What access controls are provided?

Unit-4(PRINCIPLES OF PROGRAMMING 281


LANGUAGE)
Language Examples
1. Simula 67
- Provided encapsulation, but no information
Hiding.
2. Ada
- The encapsulation construct is the package
- Packages usually have two parts:
1. Specification package (the interface)
[Link] package (implementation of the entities
named in the specification.

Unit-4(PRINCIPLES OF PROGRAMMING 282


LANGUAGE)
Evaluation of Ada Abstract Data Types

1. Lack of restriction to pointers is better


- Cost is recompilation of clients when the
representation is changed.
2. Cannot import specific entities from other
Packages.

Unit-4(PRINCIPLES OF PROGRAMMING 283


LANGUAGE)
Parameterized Abstract Data Types
1. Ada Generic Packages
- Make the stack type more flexible by making
the element type and the size of the stack
generic.
---> SHOW GENERIC_STACK package and two
instantiations .

Unit-4(PRINCIPLES OF PROGRAMMING 284


LANGUAGE)
C++ Templated Classes
- Classes can be somewhat generic by writing parameterized constructor
functions.
stack (int size) {
stk_ptr = new int [size];
max_len = size - 1;
top = -1;
}
stack (100) stk;
- The stack element type can be parameterized by making the class a
templated class.
---> SHOW the templated class stack .
- Java does not support generic abstract data types

Unit-4(PRINCIPLES OF PROGRAMMING 285


LANGUAGE)
Object Oriented Programming in
Smalltalk
Type Checking and Polymorphism:
- All bindings of messages to methods is dynamic.
- The process is to search the object to which the message is sent
for the method; if not found, search the superclass, etc.
- Because all variables are typeless, methods are all polymorphic
- Inheritance.
- All subclasses are subtypes (nothing can be hidden).
- All inheritance is implementation inheritance.
- No multiple inheritance.
- Methods can be redefined, but the two are not related.

Unit-4(PRINCIPLES OF PROGRAMMING 286


LANGUAGE)
C++
General Characteristics:
- Mixed typing system.
- Constructors and destructors.
- Elaborate access controls to class entities.
- Inheritance:
- A class need not be subclasses of any class.
- Access controls for members are:
1. Private (visible only in the class and friends).
2. Public (visible in subclasses and clients).
3. Protected (visible in the class and in subclasses).
- In addition, the subclassing process can be declared with access
controls, which define potential changes in access by subclasses.
- Multiple inheritance is suUpnp4-to
i P( rRtNI eCIdPEL .S OF
445
Jav
Dynamic Binding a
- In Java, all messages are dynamically bound to methods, unless
the method is final.
- Encapsulation
- Two constructs, classes and packages.
- Packages provide a container for classes that are related.
- Entities defined without an scope (access) modifier have
package scope, which makes them visible throughout the
package in which they are defined
- Every class in a package is a friend to the package scope entities
elsewhere in the package.

Unit-4(PRINCIPLES OF PROGRAMMING 288


LANGUAGE)
Ada 95
Example:
with PERSON_PKG; use PERSON_PKG;
package STUDENT_PKG is
type STUDENT is new PERSON with
record
GRADE_POINT_AVERAGE : FLOAT;
GRADE_LEVEL : INTEGER;
end record;
procedure DISPLAY (ST: in STUDENT);
end STUDENT_PKG;
- DISPLAY is being overriden from
PERSON_PKG
- All subclasses are subtypes
- Single inheritance only, except
Unit-4(PRINCIPLES OF PROGRAMMING 289
through generics LANGUAGE)
Concurrency
Def: A thread of control in a program is the sequence of program
points reached as control flows through the program.
Categories of Concurrency:
[Link] concurrency - Multiple independent processors
( multiple threads of control).
2. Logical concurrency - The appearance of physical concurrency
is presented by timesharing one processor (software can be
designed as if there were multiple threads of control).
- Coroutines provide only quasiconcurrency.

Unit-4(PRINCIPLES OF PROGRAMMING 290


LANGUAGE)
Reasons to Study Concurrency
1. It involves a new way of designing
software that can be very useful--many
real-world situations involve concurrency.
2. Computers capable of physical
concurrency are now widely used.

Unit-4(PRINCIPLES OF PROGRAMMING 291


LANGUAGE)
Design Issues for Concurrency
[Link] is cooperation synchronization
provided?
2. How is competition synchronization
provided?
[Link] and when do tasks begin and end
execution?
4. Are tasks statically or dynamically
created?
Unit-4(PRINCIPLES OF PROGRAMMING 292
LANGUAGE)
Methods of Providing Synchronization

1. Semaphores
2. Monitors
3. Message Passing

Unit-4(PRINCIPLES OF PROGRAMMING 293


LANGUAGE)
Semaphores
Semaphores (Dijkstra - 1965).
-A semaphore is a data structure consisting of a
counter and a queue for storing task descriptors.
- Semaphores can be used to implement guards on the
code that accesses shared data structures.
- Semaphores have only two operations, wait and
release (originally called P and V by Dijkstra).
-Semaphores can be used to provide both
competition and cooperation synchronization
Unit-4(PRINCIPLES OF PROGRAMMING 294
LANGUAGE)
Example
wait(aSemaphore)
if aSemaphore’s counter > 0 then
Decrement aSemaphore’s counter
else
Put the caller in aSemaphore’s queue
Attempt to transfer control to some
ready task
(If the task ready queue is empty,
deadlock occurs)
end Unit-4(PRINCIPLES OF PROGRAMMING
LANGUAGE)
453
Example
release(aSemaphore)
if aSemaphore’s queue is empty then
Increment aSemaphore’s counter
else
Put the calling task in the task ready
queue
Transfer control to a task from
aSemaphore’s queue
end Unit-4(PRINCIPLES OF PROGRAMMING
LANGUAGE)
454
Monitors
- Competition Synchronization with Monitors:
- Access to the shared data in the monitor is
limited by the implementation to a single
process at a time; therefore, mutually
exclusive access is inherent in the semantic
definition of the monitor.
- Multiple calls are queued.

Unit-4(PRINCIPLES OF PROGRAMMING 297


LANGUAGE)
Monitors
Cooperation Synchronization with Monitors:
- Cooperation is still required - done with semaphores, using the queue data
type and the built-in operations, delay (similar to send) and continue
(similar to release).
- delay takes a queue type parameter; it puts the process that calls it in the
specified queue and removes its exclusive access rights to the monitor’s
data structure.
- Differs from send because delay always blocks the caller.
- continue takes a queue type parameter; it disconnects the caller from the
monitor, thus freeing the monitor for use by another process.
-It also takes a process from the parameter.
-queue (if the queue isn’t empty) and starts it.
-Differs from release because it always has some effect (release does nothing
if the queue is empty).
Unit-4(PRINCIPLES OF PROGRAMMING 298
LANGUAGE)
Message Passing
Competition Synchronization with Message Passing:
- Example:
- a shared buffer.
- Encapsulate the buffer and its operations in a task.
- Competition synchronization is implicit in the
semantics of accept clauses.
- Only one accept clause in a task can be active at any
given time.

Unit-4(PRINCIPLES OF PROGRAMMING 299


LANGUAGE)
Java Threads
Competition Synchronization with Java Threads:
- A method that includes the synchronized modifier disallows
any other method from running on the object while it is in
execution.
- If only a part of a method must be run without interference, it
can be synchronized.
- Cooperation Synchronization with Java Threads:
- The wait and notify methods are defined in Object, which is the
root class in Java, so all objects inherit them.
- The wait method must be called in a loop.
Example - the queue.

Unit-4(PRINCIPLES OF PROGRAMMING 300


LANGUAGE)
Exception Handling
In a language without exception handling:
➢When an exception occurs, control goes to
the
operating system, where a message is displayed
and the program is terminated.
In a language with exception handling:
➢Programs are allowed to trap some
exceptions, thereby providing the possibility
of fixing the problem and continuing.
Unit-4(PRINCIPLES OF PROGRAMMING 301
LANGUAGE)
Design Issues for Exception Handling
1. How and where are exception handlers specified and what is
their scope?
2. How is an exception occurrence bound to an exception
handler?
3. Where does execution continue, if at all, after an exception
handler completes its execution?
4. How are user-defined exceptions specified?
5. Should there be default exception handlers for programs that
do
not provide their own?
6. Can built-in exceptions be explicitly raised?
7. Are hardware-detectable errors treated as exceptions that can be
handled?
8. Are there any built-in Unit-4(PRINCIPLES
exceptions? OF PROGRAMMING 302
LANGUAGE)
Ada Exception Handling
Def: The frame of an exception handler in Ada is either a subprogram body, a
package body, a task, or a block.
- Because exception handlers are usually local to the code in which the
exception can be raised, they do not have parameters.
- Handler form:
exception
when exception_name {| exception_name} =>
statement_sequence
...
when ...
...
[when others =>statement_sequence ]
- Handlers are placed at the end of the block
or unit in which they occur.
Unit-4(PRINCIPLES OF PROGRAMMING 303
LANGUAGE)
Binding Exceptions to Handlers
➢If the block or unit in which an exception is raised
does not have a handler for that exception, the
exception is propagated elsewhere to be handled.
1. Procedures - propagate it to the caller.
2. Blocks - propagate it to the scope in which it
occurs.
3. Package body - propagate it to the declaration part
of the unit that declared the package (if it is a library
unit (no static parent), the program is terminated).
4. Task - no propagation; if it has no handler, execute it;
in either case, mark it "completed“.
Unit-4(PRINCIPLES OF PROGRAMMING 304
LANGUAGE)
C++ Exception Handling
try {
-- code that is expected to raise an exception}
catch (formal parameter) {
-- handler code
}…..
catch (formal parameter) {
-- handler code
}
- catch is the name of all handlers--it is an overloaded name, so the formal
parameter of each must be unique.
- The formal parameter need not have a variable.
- It can be simply a type name to distinguish the handler it is in from
others.
- The formal parameter can be used to transfer information to the handler.
Unit-4(PRINCIPLES OF PROGRAMMING 305
LANGUAGE)
Java Exception Handling
The finally Clause:
- Can appear at the end of a try construct
- Form:
finally {
...
}
- Purpose: To specify code that is to be executed, regardless of what happens
in the try construct.
- A try construct with a finally clause can be used outside exception handling
try {
for (index = 0; index < 100; index++) {

if (…) {
return;
}
Unit-4(PRINCIPLES OF PROGRAMMING 306
LANGUAGE)
Evaluatio
n
-The types of exceptions makes more sense
than in the case of C++.
-The throws clause is better than that of C++
(The throw clause in C++ says little to the
programmer).
- The finally clause is often useful.
-The Java interpreter throws a variety of
exceptions that can be handled by user
programs. Unit-4(PRINCIPLES OF PROGRAMMING 307
LANGUAGE)
Introduction to logic programming
Logic programming languages, sometimes called declarative programming
Languages.
Express programs in a form of symbolic logic.
Use a logical inferencing process to produce results.
Declarative rather that procedural:
–Only specification of results are stated (not detailed procedures for
producing them).
Proposition:
A logical statement that may or may not be true.
–Consists of objects and relationships of objects to each other.
Symbolic Logic:
Logic which can be used for the basic needs of formal logic:
–Express propositions.
–Express relationships between propositions.
–Describe how new propositions can be inferred from other propositions.
(Particular form of symbolic logic used for logic programming called predicate
Unit-4(PRINCIPLES OF PROGRAMMING
Calculus) LANGUAGE)
308
Object Representation
Objects in propositions are represented by simple terms: either constants or
variables.
Constant: a symbol that represents an object.
Variable: a symbol that can represent different objects at different times.
–Different from variables in imperative languages.
Compound Terms:
Atomic propositions consist of compound terms.
Compound term: one element of a mathematical relation, written like a
mathematical function.
–Mathematical function is a mapping.
–Can be written as a table.
Parts of a Compound Term:
Compound term composed of two parts:
Unit-4(PRINCIPLES OF PROGRAMMING 309
LANGUAGE)
Example
Functor: function symbol that names the
relationship.
–Ordered list of parameters (tuple).
Examples:
student(jon)
like(seth, OSX)
like(nick, windows)
like(jim, linux)
Unit-4(PRINCIPLES OF PROGRAMMING 310
LANGUAGE)
Forms of a Proposition
Propositions can be stated in two forms:
–Fact: proposition is assumed to be true.
–Query: truth of proposition is to be
determined.
Compound proposition:
–Have two or more atomic
propositions.
–Propositions are connected by
operators. Unit-4(PRINCIPLES OF PROGRAMMING 311
LANGUAGE)
Clausal Form
Too many ways to state the same thing
-Use a standard form for propositions.
Clausal form:
–B1 B2 … Bn A1 A2 … Am
–means if all the As are true, then at least one B
is true.
Antecedent: right side.
Consequent: left side.
Unit-4(PRINCIPLES OF PROGRAMMING 312
LANGUAGE)
Predicate Calculus and Proving Theorems

-use of propositions is to discover new theorems that can be


inferred from known axioms and theorems.
Resolution: an inference principle that allows inferred
propositions to be computed from given propositions
resolution.
Unification: finding values for variables in propositions that
allows matching process to succeed.
Instantiation: assigning temporary values to variables to allow
unification to succeed after instantiating a variable with a
value, if matching fails, may need to backtrack and instantiate
with a different value.

Unit-4(PRINCIPLES OF PROGRAMMING 313


LANGUAGE)
Theorem Proving
-Basis for logic programming.
-When propositions used for resolution, only
restricted form can be used.
Horn clause - can have only two forms.
–Headed: single atomic proposition on left
side.
–Headless: empty left side (used to state
facts).
-Most propositions can be stated as Horn
Unit-4(PRINCIPLES OF PROGRAMMING 314
clauses. LANGUAGE)
Basic Elements of Prolog
Terms:
-Edinburgh Syntax.
Term: a constant, variable, or structure.
Constant: an atom or an integer.
Atom: symbolic value of Prolog.
Atom consists of either:
–a string of letters, digits, and underscores beginning
with a lowercase letter.
–a string of printable ASCII characters delimited by
apostrophes.
Unit-4(PRINCIPLES OF PROGRAMMING 315
LANGUAGE)
Terms: Variables and Structures
-Variable: any string of letters, digits, and
underscores beginning with an uppercase
letter.
-Instantiation: binding of a variable to a
value.
–Lasts only as long as it takes to satisfy one
complete goal.
-Structure: represents atomic proposition
functor(parameter list).
Unit-4(PRINCIPLES OF PROGRAMMING 316
LANGUAGE)
Fact Statements
-Used for the hypotheses.
-Headless Horn clauses:
female(shelley).
male(bill).
father(bill, jake).

Unit-4(PRINCIPLES OF PROGRAMMING 317


LANGUAGE)
Rule Statements
-Used for the hypotheses.
-Headed Horn clause:
Right side: antecedent (if part)
–May be single term or conjunction.
Left side: consequent (then part).
–Must be single term.
Conjunction: multiple terms separated by logical AND operations (implied)
Example Rules:
ancestor(mary,shelley):- mother(mary,shelley).
Can use variables (universal objects) to generalize meaning:
parent(X,Y):- mother(X,Y).
parent(X,Y):- father(X,Y).
grandparent(X,Z):- parent(X,Y), parent(Y,Z).
sibling(X,Y):- mother(M,X), mother(M,Y),
father(F,X), father(F,Y). Unit-4(PRINCIPLES OF PROGRAMMING 318
LANGUAGE)
Goal Statements
-For theorem proving, theorem is in form of
proposition that we want system to prove or
disprove – goal statement.
-Same format as headless Horn
eg: man(fred)
-Conjunctive propositions and propositions with
variables also legal goals.
eg: father(X,mike)
Unit-4(PRINCIPLES OF PROGRAMMING 319
LANGUAGE)
Inferencing Process of Prolog
-Queries are called goals.
-If a goal is a compound proposition, each of the facts is a
subgoal.
-To prove a goal is true, must find a chain of inference rules
and/or facts.
For goal Q:
B :- A
C :- B

Q :- P
-Process of proving a subgoal called matching, satisfying, or
resolution. Unit-4(PRINCIPLES OF PROGRAMMING
478
LANGUAGE)
Simple Arithmetic
-Prolog supports integer variables and integer arithmetic.
-is operator: takes an arithmetic expression as right operand and variable as
left operand.
eg: A is B / 17 + C
-Not the same as an assignment statement!
Example: speed(ford,100).
speed(chevy,105)
.
speed(dodge,95).
speed(volvo,80).
time(ford,20).
time(chevy,21).
time(dodge,24).
time(volvo,24).
distance(X,Y) :- speed(X,Speed),
Ytime(X,Time),
is Speed * Time. Unit-4(PRINCIPLES OF PROGRAMMING
479
LANGUAGE)
Trac
e
-Built-in structure that displays instantiations at
each step.
-Tracing model of execution - four events:
–Call (beginning of attempt to satisfy goal).
–Exit (when a goal has been satisfied).
–Redo (when backtrack occurs).
–Fail (when goal fails).

Unit-4(PRINCIPLES OF PROGRAMMING 322


LANGUAGE)
Example
likes(jake,chocolate).
likes(jake,apricots).
likes(darcie,licorice).
likes(darcie,apricots)
. trace.
likes(jake,X),
likes(darcie,X).

Unit-4(PRINCIPLES OF PROGRAMMING 323


LANGUAGE)
Bindings and scope
• A PROLOG program consists of one or more
relations.
• The scope of every relation is the entire
program.
• It is not possible in PROLOG to define a
relation locally to another relation, nor to
group relations into packages.

Unit-4(PRINCIPLES OF PROGRAMMING 324


LANGUAGE)
Contro
l
• In principle, the order in which resolution is
done should not affect the set of answers
yielded by a query (although it will affect the
order in which these answers are found).
• In practical logic programming, however, the
order is very important

Unit-4(PRINCIPLES OF PROGRAMMING 325


LANGUAGE)
Deficiencies of prolog
• Resolution order control
• Closed word assumption: When an assertion is
tested, therefore, success means true and failure
means either unknown or false. As this is rather
inconvenient, PROLOG bends the rules of logic by
ignoring the distinction between unknown and false.
In other words, an assertion is assumed to be false if
it cannot be inferred to be true. This is called the
closed world assumption
• Negation problem.
Unit-4(PRINCIPLES OF PROGRAMMING 326
LANGUAGE)
Applications of Logic Programming
Relational database management system:
• RDBMS stores data in the form of tables and queries.
• Prolog can replace the DML,DDL and query language
which are implanted in imperative languages.
Expert Systems
• Expert systems consists of database of facts, an
inferencing process, a human interface to look like an
expert human consultant.
• Logical programming helps to solve the
incompleteness of database.

Unit-4(PRINCIPLES OF PROGRAMMING 327


LANGUAGE)
Applications of logic

programming(cont..
Natural language processing
• Few kinds)of natural processing languages can be
done using logical programming

Unit-4(PRINCIPLES OF PROGRAMMING 328


LANGUAGE)
UNIT-5
CONCEPTS
• Introduction
• Fundamentals of FPL
• LISP
• ML
• HASKELL
• Applications of FPL
• Scripting languages

UNIT-5 (PRINCIPLES OF PROGRAMMING


330
LANGUAGES)
FUNTIONAL PROGRAMMING LANGUAGE

• The design of the imperative languages is


based directly on Von Nuemann
Architechture.
• The design of the functional language is based
on mathematical functions.

UNIT-5 (PRINCIPLES OF PROGRAMMING


331
LANGUAGES)
MATHEMATICAL FUNCTION
Def: A mathematical function is a mapping of
members of one set, called the domain set, to
another set, called the range set.
•A lambda expression specifies the parameter(s)
and the mapping of a function in the following form
l(x) x * x * x
For the function cube (x) = x * x * x
• Lambda expressions describe nameless functions

UNIT-5 (PRINCIPLES OF PROGRAMMING


332
LANGUAGES)
Mathematical function(cont..)

• Lambda expressions are applied to


parameter(s) by placing the parameter(s) after
the expression
• e.g. (l(x) x * x * x)(3) which evaluates to 27
A Function for Constructing Functions
DEFINE - Two forms:
1. To bind a symbol to an expression
e.g.,
(DEFINE pi 3.141593)
(DEFINE two_pi (* 2 pi))
UNIT-5 (PRINCIPLES OF PROGRAMMING
333
LANGUAGES)
Fundamentals of Functional
Programming Languages
• The objective of the design of a FPL is to
mimic mathematical functions to the greatest
extent possible.
• The basic process of computation is
fundamentally different in a FPL than in an
imperative language.
• In an imperative language, operations are
done and the results are stored in variables for
later use

UNIT-5 (PRINCIPLES OF PROGRAMMING


334
LANGUAGES)
Fundamentals of FPL(cont..)
• Management of variables is a constant
concern and source of complexity for
imperative programming.
• In an FPL, variables are not necessary, as is the
case in mathematics.
• In an FPL, the evaluation of a function always
produces the same result given the same
parameters.
• This is called referential transparency.
UNIT-5 (PRINCIPLES OF PROGRAMMING
335
LANGUAGES)
LISP
• The first functional programming language.
• Data object types: originally only atoms and
lists.
• List form: parenthesized collections of sublists
and/or atoms
E.g., (A B (C D) E)

UNIT-5 (PRINCIPLES OF PROGRAMMING


336
LANGUAGES)
A Bit of LISP
• Originally, LISP was a typeless language.
• There were only two data types, atom and list.
• LISP lists are stored internally as single-linked
lists.
• Lambda notation is used to specify functions
and function definitions, function
applications,and data all have the same form.

UNIT-5 (PRINCIPLES OF PROGRAMMING


337
LANGUAGES)
INTRODUCTION TO SCHEME
• A mid-1970s dialect of LISP, designed to be
cleaner, more modern, and simpler version
than the contemporary dialects of LISP.
• Uses only static scoping.
• Functions are first-class entities.
-They can be the values of expressions and
elements of lists
- They can be assigned to variables and passed
as parameters
UNIT-5 (PRINCIPLES OF PROGRAMMING 496
LANGUAGES)
Primitive Functions:
[Link]: +, -, *, /, ABS, SQRT
e.g., (+ 5 2) yields 7
2. QUOTE -takes one parameter; returns the parameter
without evaluation.
1. QUOTE is required because the Scheme interpreter,
named EVAL, always evaluates parameters to
function applications before applying the function.
QUOTE is used to avoid parameter evaluation when
it is not appropriate.

UNIT-5 (PRINCIPLES OF PROGRAMMING


339
LANGUAGES)
QUOT
• E
QUOTE can be abbreviated with the apostrophe
prefix operator
e.g., '(A B) is equivalent to (QUOTE (A B))
3. CAR takes a list parameter; returns the first
element of that list
e.g., (CAR '(A B C)) yields A
(CAR '((A B) C D)) yields (A B)
4. CDR takes a list parameter; returns the list
after removing its first element

UNIT-5 (PRINCIPLES OF PROGRAMMING


340
LANGUAGES)
Examples
e.g., (CDR '(A B C)) yields (B C)
(CDR '((A B) C D)) yields (C D)
5. CONS takes two parameters, the first of which
can be either an atom or a list and the second
of which is a list; returns a new list that
includes the first parameter as its first element
and the second parameter as the remainder
of its result

UNIT-5 (PRINCIPLES OF PROGRAMMING


341
LANGUAGES)
Examples
e.g., (CONS 'A '(B C)) returns (A B C)
6. LIST - takes any number of parameters; returns a
list with the parameters as elements.
Predicate Functions: (#T and () are true and false)
• 1. EQ? takes two symbolic parameters; it returns
#T if both parameters are atoms and the two are
the same.
• e.g., (EQ? 'A 'A) yields #T
(EQ? 'A '(A B)) yields ()

UNIT-5 (PRINCIPLES OF PROGRAMMING


342
LANGUAGES)
Examples
2. LIST? takes one parameter; it returns #T if
the parameter is an list; otherwise ()
3. NULL? takes one parameter; it returns #T if
the parameter is the empty list; otherwise ()
Note that NULL? returns #T if the parameter is ()
4. Numeric Predicate Functions =, <>, >, <, >=,
<=, EVEN?, ODD?, ZERO?
5. Output Utility Functions:
(DISPLAY expression)
(NEWLINE) UNIT-5 (PRINCIPLES OF PROGRAMMING
LANGUAGES)
343
Examples
Lambda Expressions:
Form is based on l notation
e.g., (LAMBDA (L) (CAR (CAR L)))
L is called a bound variable
Lambda expressions can be applied
e.g., ((LAMBDA (L) (CAR (CAR L)))
'((A B) C D))

UNIT-5 (PRINCIPLES OF PROGRAMMING


344
LANGUAGES)
Examples
2. To bind names to lambda expressions
e.g.,(DEFINE (cube x) (* x x x))
Example use:(cube 4)
- Evaluation process (for normal
functions):
1. Parameters are evaluated, in no particular
order.
2. The values of the parameters are
substituted into the function body.
3. The function body is evaluated.
4. The
bodyvalue
is the of the
valu last
UNeIT-5 o(Pfexpression
RINtChIPLeES in
503
the
OfF uPRnOGcRAtMiMoINnG .
Examples
Control Flow:
1. Selection- the special form, IF
(IF predicate then_exp else_exp)
e.g.,(IF (<> count 0)
(/ sum count)
0
)

UNIT-5 (PRINCIPLES OF PROGRAMMING


346
LANGUAGES)
Examples
2. Multiple Selection - the special form, COND
- General form:
- (COND
(predicate_1 expr {expr})
(predicate_1 expr
{expr})
...
(predicate_1 expr {expr})
(ELSE expr {expr})
)
- Returns the valueUNIT-5
of (PRINCIPLES
the OF PROGRAMMING 347
LANGUAGES)
COMMON LISP
• A combination of many of the features of the
popular dialects of LISP around in the early 1980s.
• A large and complex language--the opposite of
Scheme.
• Includes: records, arrays, Complex numbers,
character strings, powerful i/o capabilities,
packages with access control, imperative features
like those of Scheme ,iterative control statements.

UNIT-5 (PRINCIPLES OF PROGRAMMING


348
LANGUAGES)
ML
• A static-scoped functional language with
syntax that is closer to Pascal than to LISP
• Uses type declarations, but also does type
inferencing to determine the types of
undeclared
• It is strongly typed (whereas Scheme
is essentially typeless) and has no type
coercions

UNIT-5 (PRINCIPLES OF PROGRAMMING


349
LANGUAGES)
ML(cont..)

• Includes exception handling and a module facility


for implementing abstract data types
• Includes lists and list operations
•The val statement binds a name to a value
(similar to DEFINE in Scheme)
• Function declaration form:
fun function_name (formal_parameters) =
function_body_expression;
e.g., fun cube (x : int) = x * x * x;

UNIT-5 (PRINCIPLES OF PROGRAMMING


350
LANGUAGES)
ML(cont..)
• Functions that use arithmetic or relational
operators cannot be polymorphic--those with
only list operations can be polymorphic

UNIT-5 (PRINCIPLES OF PROGRAMMING


351
LANGUAGES)
Haskell
• Similar to ML (syntax, static scoped, strongly
typed, type inference)
• Different from ML (and most other
functional languages) in that it is PURELY
functional
(e.g., no variables, no assignment statements,
and no side effects of any kind)
Most Important Features
• Uses lazy evaluation
• Has “list comprehensions,” which allow it to
• deal with infinite lists
UNIT-5 (PRINCIPLES OF PROGRAMMING
352
LANGUAGES)
HASKELL(cont..)
Examples
1. Fibonacci numbers (illustrates function definitions with
different parameter forms)
fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n
[Link] evaluation
Infinite lists
e.g., positives = [0..]
squares = [n * n | n ¨
[0..]]
(only compute those
that are necessary)
UNIT-5 (PRINCIPLES OF PROGRAMMING
353
LANGUAGES)
Applications of Functional Languages
• APL is used for throw-away programs.
• LISP is used for artificial intelligence
- Knowledge representation
- Machine learning
- Natural language processing
- Modeling of speech and vision
• Scheme is used to teach introductory
programming at a significant number of
universities.

UNIT-5 (PRINCIPLES OF PROGRAMMING


354
LANGUAGES)
Comparing Functional and Imperative
Languages
Imperative Languages:
- Efficient execution
- Complex semantics
- Complex syntax
- Concurrency is programmer designed
Functional Languages:
- Simple semantics
- Simple syntax
- Inefficient execution
- Programs can automatically be made concurrent

UNIT-5 (PRINCIPLES OF PROGRAMMING


355
LANGUAGES)
Scripting languages
Pragmatics
• Scripting is a paradigm characterized by:
-use of scripts to glue subsystems together;
-rapid development and evolution of scripts;
-modest efficiency requirements;
-very high-level functionality in application-
specific areas.

UNIT-5 (PRINCIPLES OF PROGRAMMING


356
LANGUAGES)
Scripting languages(cont.)

• A software system often consists of a number


of subsystems controlled or connected by a
script.
• In such a system, the script is said to glue the
sub systems together.

UNIT-5 (PRINCIPLES OF PROGRAMMING


357
LANGUAGES)
PYTHON
• PYTHON was designed in the early 1990s
by Guido van Rossum.
• PYTHON borrows ideas from languages as
diverse as PERL ,HASKELL ,and the object-
oriented languages, skillfully integrating these
ideas into a coherent whole.
• PYTHON scripts are concise but readable, and
highly expressive.

UNIT-5 (PRINCIPLES OF PROGRAMMING


358
LANGUAGES)
Values and types
• PYTHON has a limited repertoire of primitive
types: integer, real, and complex Numbers.
• It has no specific character type; single-
character strings are used instead.
• its boolean values (named False and True) are
just small integers.
• PYTHON has a rich repertoire of composite
types: tuples, strings, lists, dictionaries, and
objects.
UNIT-5 (PRINCIPLES OF PROGRAMMING
359
LANGUAGES)
Variables, storage, and control
• PYTHON supports global and local variables.
• Variables are not explicitly declared, simply
initialized by assignment.
• PYTHON adopts reference semantics. This is
especially significant for mutable values, which
can be selectively updated.
• Primitive values and strings are immutable; lists,
dictionaries, and objects are mutable; tuples are
mutable if any of their components are mutable.
UNIT-5 (PRINCIPLES OF PROGRAMMING
360
LANGUAGES)
Examples
• PYTHON’s repertoire of commands include
assignments, procedure calls, conditional (if-
but not case-) commands, iterative (while- and
for-) commands, and exception-handling
commands.
• PYTHON if- and while-commands are
conventional.

UNIT-5 (PRINCIPLES OF PROGRAMMING


361
LANGUAGES)
Pythons reserved words
and assert break class continue def
del elif
else except exec finally for from global
if import in is lambda
not or pass
print
raise return try while yield

UNIT-5 (PRINCIPLES OF PROGRAMMING


362
LANGUAGES)
Dynamically typed language
• Python is a dynamically typed language. Based
on the value, type of the variable is during the
execution of the program.
Python(dynamic)
C=1
C = [1,2,3]
C(static)
Double c; c = 5.2;

UNIT-5 (PRINCIPLES OF PROGRAMMING


363
LANGUAGES)
Strongly typed python
language:
• Weakly Vs strongly typed python language
differ in their automatic conversions.
Perl(weak)
$b = `1.2`
$c = 5 * $b;
Python(strong)
b =`1.2`
c= 5*
b;
UNIT-5 (PRINCIPLES OF PROGRAMMING
364
LANGUAGES)
Bindings and scope
• A PYTHON program consists of a number of
modules, which may be grouped into packages.
• Within a module we may initialize variables,
define procedures, and declare classes
• Within a procedure we may initialize local
variables and define local procedures.
• Within a class we may initialize variable
components and define procedures (methods).
• PYTHON was originally a dynamically-scoped
language, but it is now statically scoped.
UNIT-5 (PRINCIPLES OF PROGRAMMING
365
LANGUAGES)
Binding and scope
• In python, variables defined inside the function are
local to that function. In order to change them as
global variables, they must be declared as global inside
the function as given below.
S=1
Def
myfunc(x,y); Z =
0

Global
s;
S=2
Return
y-1 , z+1; UNIT-5 (PRINCIPLES OF PROGRAMMING
366
LANGUAGES)
Procedural abstraction
• PYTHON supports function procedures and
proper procedures.
• The only difference is that a function
procedure returns a value, while a proper
procedure returns nothing.
• Since PYTHON is dynamically typed, a
procedure definition states the name but not
the type of each formal parameter.

UNIT-5 (PRINCIPLES OF PROGRAMMING


367
LANGUAGES)
Python procedure
Eg :Def gcd (m, n):
p,q=m,n
while p%q!=0:
p,q=q,p%q
return q

UNIT-5 (PRINCIPLES OF PROGRAMMING


368
LANGUAGES)
Python procedure with Dynamic Typing
Eg: def minimax (vals):
min = max = vals[0]
for val in vals:
if val <
min: min =
val
elif val
> max:
max = val return
min, max UNIT-5 (PRINCIPLES OF PROGRAMMING
LANGUAGES)
369
Data Abstraction
• PYTHON has three different constructs
relevant to data abstraction: packages
,modules , and classes
• Modules and classes support encapsulation,
using a naming convention to distinguish
between public and private components.
• A Package is simply a group of modules
• A Module is a group of components that may
be variables, procedures, and classes
UNIT-5 (PRINCIPLES OF PROGRAMMING
370
LANGUAGES)
Data abstraction(cont..)
• A Class is a group of components that may be
class variables, class methods ,and instance
methods.
• A procedure defined in a class declaration acts
as an instance method if its first formal
parameter is named self and refers to an
object of the class being declared. Otherwise
the procedure acts as a class method.

UNIT-5 (PRINCIPLES OF PROGRAMMING


371
LANGUAGES)
Data abstraction(cont..)
• To achieve the effect of a constructor, we
usually equip each class with an initialization
method named ‘‘_init_’’; this method is
automatically called when an object of the
class is constructed.
• PYTHON supports multiple inheritance: a class
may designate any number of superclasses.

UNIT-5 (PRINCIPLES OF PROGRAMMING


372
LANGUAGES)
Separate Compilation
• PYTHON modules are compiled separately.
• Each module must explicitly import every
other module on which it depends
• Each module’s source code is stored in a text
file. Eg: [Link]
• When that module is first imported, it is
compiled and its object code is stored in a file
named [Link]

UNIT-5 (PRINCIPLES OF PROGRAMMING


373
LANGUAGES)
Separate Compilation(cont..)
• Compilation is completely automatic
• The PYTHON compiler does not reject code that
refers to undeclared [Link] code simply
fails if and when it is executed
• The compiler will not reject code that might fail
with a type error,nor even code that will certainly
fail, such as:
def fail
(x): print
x+1,
x[0] UNIT-5 (PRINCIPLES OF PROGRAMMING
374
LANGUAGES)
Module Library
• PYTHON is equipped with a very rich module
library, which supports string handling
,markup , mathematics, cryptography,
multimedia, GUIs, operating system services
,internet services, compilation, and so on.
• Unlike older scripting languages, PYTHON
does not have built-in high-level string
processing or GUI support , so module library
provides it.

UNIT-5 (PRINCIPLES OF PROGRAMMING


375
LANGUAGES)

You might also like