Principles of Programming Languages
Principles of Programming Languages
in
UNIT-I
Preliminaries
Topics
1. Reasons for Studying Concepts of Programming Languages
2. Programming Domains
3. Language Evaluation Criteria
4. Influences on Language Design
5. Language Categories
6. Language Design Trade-Offs
7. Implementation Methods
8. Programming Environments
`
Background
―Frankly, we didn‘t have the vaguest idea how the thing [FORTRAN language
and compiler] would work out in detail. …We struck out simply to optimize the object
program, the running time, because most people at that time believed you couldn‘t do
that kind of thing. They believed that machined-coded programs would be so
inefficient that it would be impractical for many applications.‖
-John Backus
• Scientific applications
– Large number of floating point computations
– Fortran
• Business applications
– Produce reports, use decimal numbers and characters
– COBOL
• Artificial intelligence
– Symbols rather than numbers manipulated
– LISP
• Systems programming
– Need efficiency because of continuous use
1
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• 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 cost
Evaluation Criteria: Readability
• Overall simplicity
– A manageable set of features and constructs
– Few feature multiplicity (means of doing the same operation)
– 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
• Control statements
– The presence of well-known control structures (e.g., while statement)
• Data types and structures
– The presence of adequate facilities for defining data structures
• Syntax considerations
– Identifier forms: flexible composition
– Special words and methods of forming compound statements
– Form and meaning: self-descriptive constructs, meaningful keywords
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
– Example: the inclusion of for statement in many modern 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 necessarily use ―unnatural‖ approaches, and hence reduced reliability
2
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• 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
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
The von Neumann Architecture
3
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• Imperative
– Central features are variables, assignment statements, and iteration
– Examples: C, Pascal
• 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
• Object-oriented
– Data abstraction, inheritance, late binding
– Examples: Java, C++
• Markup
– New; not a programming per se, but used to specify the layout of
information in Web documents
– Examples: XHTML, XML
• Compilation
4
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
The operating system and language implementation are layered over Machine interface
of a computer
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
5
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• Load module (executable image): the user and system code together
• Linking and loading: the process of collecting system program and linking them
to user program
6
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
7
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
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
8
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
UNIT-2
Syntax and Semantics
2.1 Introduction
Syntax: the form or structure of the expressions, statements, and program
units
Semantics: the meaning of the expressions, statements, and program units
Syntax and semantics provide a language‘s definition
o Users of a language definition
Other language designers
Implementers
Programmers (the users of the language)
BNF Fundamentals
Non-terminals: BNF abstractions
Terminals: lexemes and tokens
Grammar: a collection of rules
o Examples of BNF rules:
<ident_list> → identifier | identifer, <ident_list>
<if_stmt> → if <logic_expr> then <stmt>
BNF Rules
A rule has a left-hand side (LHS) and a right-hand side (RHS), and consists of
terminal and nonterminal symbols
A grammar is a finite nonempty set of rules
An abstraction (or nonterminal symbol) can have more than one RHS
<stmt> <single_stmt>
| begin <stmt_list> end
Describing Lists
Syntactic lists are described using recursion
<ident_list> ident
| ident, <ident_list>
A derivation is a repeated application of rules, starting with the start symbol
and ending with a sentence (all terminal symbols)
An Example Grammar
<program> <stmts>
<stmts> <stmt> | <stmt> ; <stmts>
<stmt> <var> = <expr>
<var> a|b|c|d
<expr> <term> + <term> | <term> - <term>
<term> <var> | const
An example derivation
<program> => <stmts> => <stmt>
<var> = <expr> => a =<expr>
10
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Derivation
Every string of symbols in the derivation is a sentential form
A sentence is a sentential form that has only terminal symbols
A leftmost derivation is one in which the leftmost nonterminal in each
sentential form is the one that is expanded
A derivation may be neither leftmost nor rightmost
Parse Tree
A hierarchical representation of a derivation
Ambiguity in Grammars
A grammar is ambiguous iff it generates a sentential form that has two or more
distinct parse trees
11
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Associativity of Operators
Operator associativity can also be indicated by a grammar
Extended BNF
Optional parts are placed in brackets ([ ])
<proc_call> -> ident [(<expr_list>)]
Alternative parts of RHSs are placed inside parentheses and separated via
vertical bars
<term> → <term> (+|-) const
Repetitions (0 or more) are placed inside braces ({ })
<ident> → letter {letter|digit}
BNF and EBNF
BNF
<expr> <expr> + <term>
| <expr> - <term>
| <term>
<term> <term> * <factor>
| <term> / <factor>
| <factor>
EBNF
<expr> <term> {(+ | -) <term>}
<term> <factor> {(* | /) <factor>}
Semantic rules:
<expr>.actual_type <var>[1].actual_type
Predicate:
<var>[1].actual_type == <var>[2].actual_type
<expr>.expected_type == <expr>.actual_type
<expr>.actual_type <var>[1].actual_type
<expr>.actual_type =? <expr>.expected_type
2.5 Semantics
There is no single widely acceptable notation or formalism for describing
semantics
Operational Semantics
o Describe the meaning of a program by executing its statements on a
machine, either simulated or actual. The change in the state of the
machine (memory, registers, etc.) defines the meaning of the statement
To use operational semantics for a high-level language, a virtual machine is
needed
A hardware pure interpreter would be too expensive
A software pure interpreter also has problems:
o The detailed characteristics of the particular computer would make
actions difficult to understand
o Such a semantic definition would be machine- dependent
Operational Semantics
A better alternative: A complete computer simulation
The process:
o Build a translator (translates source code to the machine code of an
idealized computer)
o Build a simulator for the idealized computer
Evaluation of operational semantics:
o Good if used informally (language manuals, etc.)
o Extremely complex if used formally (e.g., VDL), it was used for describing
semantics of PL/I.
Axiomatic Semantics
o Based on formal logic (predicate calculus)
o Original purpose: formal program verification
o Approach: Define axioms or inference rules for each statement type in
the language (to allow transformations of expressions to other
expressions)
o The expressions are called assertions
Axiomatic Semantics
An assertion before a statement (a precondition) states the relationships and
constraints among variables that are true at that point in execution
An assertion following a statement is a postcondition
A weakest precondition is the least restrictive precondition that will guarantee
the postcondition
15
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Program proof process: The postcondition for the whole program is the desired
result. Work back through the program to the first statement. If the
precondition on the first statement is the same as the program spec, the
program is correct.
o Let VARMAP be a function that, when given a variable name and a state,
returns the current value of the variable
VARMAP(ij, s) = vj
Decimal Numbers
o The following denotational semantics description maps decimal numbers
as strings of symbols into numeric values
<dec_num> 0|1|2|3|4|5|6|7|8|9
| <dec_num> (0 | 1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 | 9)
Expressions
Map expressions onto Z {error}
We assume expressions are decimal numbers, variables, or binary expressions
having one arithmetic operator and two operands, each of which can be an
expression
Me(<expr>, s) =
case <expr> of
<dec_num> => Mdec(<dec_num>, s)
<var> =>
if VARMAP(<var>, s) == undef
then error
else VARMAP(<var>, s)
<binary_expr> =>
if (Me(<binary_expr>.<left_expr>, s) == undef
17
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Assignment Statements
o Maps state sets to state sets
Ma(x := E, s) =
if Me(E, s) == error
then error
else s‘ = {<i1‘,v1‘>,<i2‘,v2‘>,...,<in‘,vn‘>},
where for j = 1, 2, ..., n,
vj‘ = VARMAP(ij, s) if ij <> x
= Me(E, s) if ij == x
Logical Pretest Loops
o Maps state sets to state sets
Ml(while B do L, s) =
if Mb(B, s) == undef
then error
else if Mb(B, s) == false
then s
else if Msl(L, s) == error
then error
else Ml(while B do L, Msl(L, s))
The meaning of the loop is the value of the program variables after the
statements in the loop have been executed the prescribed number of times,
assuming there have been no errors
In essence, the loop has been converted from iteration to recursion, where the
recursive control is mathematically defined by other recursive state mapping
functions
Recursion, when compared to iteration, is easier to describe with mathematical
rigor
Evaluation of denotational semantics
o Can be used to prove the correctness of programs
o Provides a rigorous way to think about programs
o Can be an aid to language design
o Has been used in compiler generation systems
o Because of its complexity, they are of little use to language users
Summary
18
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
19
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
UNIT-III
Data types
Topics
• Introduction
• Primitive Data Types
• Character String Types
• User-Defined Ordinal Types
• Array Types
• Associative Arrays
• Record Types
• Union Types
• Pointer and Reference Types
• Names
• Variables
• The Concept of Binding
• Type Checking
• Strong Typing
• Type Compatibility
• Scope
• Scope and Lifetime
• Referencing Environments
• Named Constants
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?
20
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•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
Primitive Data Types: Character
•Stored as numeric codings
•Most commonly used coding: ASCII
•An alternative, 16-bit coding: Unicode
–Includes characters from most natural languages
–Originally used in Java
–C# and JavaScript also support Unicode
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?
Character String Types Operations
•Typical operations:
–Assignment and copying
–Comparison (=, >, etc.)
–Catenation
–Substring reference
–Pattern matching
Character String Type in Certain Languages
•C and C++
22
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
–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
–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
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;
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
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.
• Static: subscript ranges are statically bound and storage allocation is static
(before 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)
Subscript Binding and Array Categories (continued)
•Heap-dynamic: binding of subscript ranges and storage allocation is dynamic
and can change any number of times
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
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)
–For example, + operator between two arrays results in an array of the sums of
the element pairs of the two arrays
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
Slice Examples
•Fortran 95
Integer, Dimension (10) :: Vector
Integer, Dimension (3, 3) :: Mat
Integer, Dimension (3, 3) :: Cube
Implementation of Arrays
•Access function maps subscript expressions to an address in the array
29
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Compile-Time Descriptors
30
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Associative Arrays
•An associative array is an unordered collection of data elements that are
indexed by an equal number of values called keys
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
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.
References to Records
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
Evaluation and Comparison to Arrays
32
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
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?
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
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;
33
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
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
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Reference Types
•C++ includes a special kind of pointer type called a reference type that is
used primarily for formal parameters
36
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Representations of Pointers
•Large computers use single values
•Intel microprocessors use segment and offset
Dangling Pointer Problem
–Heap-dynamic variables are represented as variable plus cell for integer lock
value
Heap Management
•A very complex run-time process
•Single-size cells vs. variable-size cells
•Two approaches to reclaim garbage
37
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Reference Counter
•Reference counters: maintain a counter in every cell that store the number of
pointers currently pointing at the cell
Mark-Sweep
Marking Algorithm
38
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
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
Names
Design issues for names:
Maximum length?
Are connector characters allowed?
Are names case sensitive?
Are special words reserved words or keywords?
Length
If too short, they cannot be connotative
Language examples:
FORTRAN I: maximum 6
COBOL: maximum 30
FORTRAN 90 and ANSI C: maximum 31
Ada and Java: no limit, and all are significant
C++: no limit, but implementors often impose one
Connectors
Pascal, Modula-2, and FORTRAN 77 don't allow
39
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Variables
A variable is an abstraction of a memory cell
Variables can be characterized as a sextuple of attributes:
(name, address, value, type, lifetime, and scope)
Name - not all variables have them (anonymous)
Address - the memory address with which it is associated (also called l-value)
A variable may have different addresses at different times during execution
A variable may have different addresses at different places in a program
If two variable names can be used to access the same memory location, they are
called aliases
Aliases are harmful to readability (program readers must remember all of them)
How aliases can be created:
Pointers, reference variables, C and C++ unions, (and through parameters -
discussed in Chapter 9)
Some of the original justifications for aliases are no longer valid; e.g. memory
reuse in FORTRAN
Replace them with dynamic allocation
Type - determines the range of values of variables and the set of operations that are
defined for values of that type; in the case of floating point, type also determines the
precision
Value - the contents of the location with which the variable is associated
Abstract memory cell - the physical cell or collection of cells associated with a
variable
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
42
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Strong Typing
Advantage of strong typing: allows the detection of the misuses of variables that
result in type errors
Language examples:
FORTRAN 77 is not: parameters, EQUIVALENCE
Pascal is not: variant records
C and C++ are not: parameter type checking can be avoided; unions are not
type checked
Ada is, almost (UNCHECKED CONVERSION is loophole)
(Java is similar)
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
Type Compatibility
Our concern is primarily for structured types
Def: Name type compatibility means the two variables have compatible 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 compatible with integer types
Formal parameters must be the same type as their corresponding actual
parameters (Pascal)
Structure type compatibility means that two variables have compatible types if their
types have identical structures
More flexible, but harder to implement
Consider the problem of two structured types:
Are two record types compatible if they are structurally the same but use
different field names?
Are two array types compatible if they are the same except that the subscripts
are different?
(e.g. [1..10] and [0..9])
Are two enumeration types compatible if their components are spelled
differently?
With structural type compatibility, you cannot differentiate between types of
the same structure (e.g. different units of speed, both float)
43
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
SUB2
...
- reference to x -
...
...
call SUB1
…
Scope Example
Static scoping
Reference to x is to MAIN's x
Dynamic scoping
Reference to x is to SUB1's x
Evaluation of Dynamic Scoping:
Advantage: convenience
Disadvantage: poor readability
45
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Named Constants
Def: A named constant is a variable that is bound to a value only when it is bound
to storage
Advantages: readability and modifiability
Used to parameterize programs
The binding of values to named constants can be either static (called manifest
constants) or dynamic
Languages:
Pascal: literals only
FORTRAN 90: constant-valued expressions
Ada, C++, and Java: expressions of any kind
Variable Initialization
Def: The binding of a variable to a value at the time it is bound to storage is called
initialization
Initialization is often done on the declaration statement
e.g., Java
int sum = 0;
Summary
• The data types of a language are a large part of what determines that
language‘s style and usefulness
Case sensitivity and the relationship of names to special words represent design
46
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Variables are characterized by the sextuples: name, address, value, type, lifetime,
scope
Scalar variables are categorized as: static, stack dynamic, explicit heap dynamic,
implicit heap dynamic
47
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
UNIT-IV
Expressions and Statements
•Introduction
•Arithmetic Expressions
•Overloaded Operators
•Type Conversions
•Relational and Boolean Expressions
•Short-Circuit Evaluation
•Assignment Statements
•Mixed-Mode Assignment
•Control Structures
•Introduction
•Selection Statements
•Iterative Statements
•Unconditional Branching
•Guarded Commands
•Conclusions
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
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
•The operator associativity rules for expression evaluation define the order in
which adjacent operators with the same precedence level are evaluated
51
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Boolean Expressions
52
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•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)
53
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Which is equivalent to
if ($flag){
$total = 0
} else {
$subtotal = 0
}
is written as
a += b
•In C, C++, and Java, the assignment statement produces a result and can be
used as operands
•An example:
while ((ch = getchar())!= EOF){…}
Mixed-Mode Assignment
•Assignment statements can also be mixed-mode, for example
int a, b;
float c;
c = a / b;
•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
–Within expressions
–Among program units
–Among program statements
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
Control Structure
55
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
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)
56
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•In Fortran 95, Ada, and Ruby, clauses are statement sequences
•Python uses indentation to define clauses
if x > y :
x=y
print "case 1"
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
Nesting Selectors (continued)
•To force an alternative semantics, compound statements may be used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;
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?
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:
•What are the type and scope of the loop variable?
59
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Should the loop parameters be evaluated only once, or once for every
iteration?
•FORTRAN 95 syntax
DO label var = start, finish [, stepsize]
•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
62
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
64
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
UNIT-V
Subprograms and Blocks
Topics
•Introduction
•Fundamentals of Subprograms
•Design Issues for Subprograms
•Local Referencing Environments
•Parameter-Passing Methods
•Parameters That Are Subprogram Names
•Overloaded Subprograms
•Generic Subprograms
•Design Issues for Functions
•User-Defined Overloaded Operators
•Coroutines
Introduction
•Two fundamental abstraction facilities
–Process abstraction
•Emphasized from early days
–Data abstraction
•Emphasized in the1980s
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
Basic Definitions
65
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
–In C++, default parameters must appear last because parameters are
positionally associated
66
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•C# methods can accept a variable number of parameters as long as they are
of the same type
–Pass-by-value
–Pass-by-result
–Pass-by-value-result
–Pass-by-reference
–Pass-by-name
Models of Parameter Passing
• Disadvantages:
–Those of pass-by-result
–Those of pass-by-value
Pass-by-Reference (Inout Mode)
• Disadvantages
•Fortran
–Always used the inout semantics model
–Before Fortran 77: pass-by-reference
–Fortran 77 and later: scalar variables are often passed by value-result
•C
70
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
–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 assigned but not referenced; those
declared in can be referenced but not assigned; in out parameters can be
referenced and assigned
•C#
–Default method: pass-by-value
–Pass-by-reference is specified by preceding both a formal parameter and its
actual parameter with ref
71
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• Formal parameter that are arrays have a declaration after the header
Overloaded Subprograms
73
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•An overloaded subprogram is one that has the same name as another
subprogram in the same referencing environment
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
•The above template can be instantiated for any type for which operator > is
defined
Coroutines
•Also called symmetric control: caller and called coroutines are on a more
equal basis
75
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
76
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Summary
77
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
UNIT-VI
Abstract Data types
Topics
• Language Examples
• Encapsulation Constructs
• Naming Encapsulations
• Object-Oriented Programming
• Concurrency Introduction
• Semaphores
• Monitors
• Message Passing
78
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• Java Threads
• C# Threads
• Statement-Level Concurrency
–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
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
An Example in Ada
package Stack_Pack is
type stack_type is limited private;
max_size: constant := 100;
function empty(stk: in stack_type) return Boolean;
procedure push(stk: in out stack_type; elem:in Integer);
procedure pop(stk: in out stack_type);
function top(stk: in stack_type) return Integer;
–Functions to initialize the data members of instances (they do not create the
objects)
–Necessary in C++
Language Examples: Java
•Similar to C++, except:
–All user-defined types are classes
–All objects are allocated from the heap and accessed through reference
variables
–Java has a second scoping mechanism, package scope, which can be used in
place of friends
•All entities in all classes in a package that do not have access control
modifiers are visible throughout the package
An Example in Java
class StackClass {
private:
private int [] *stackRef;
private int [] maxLen, topIndex;
public StackClass() { // a constructor
stackRef = new int [100];
maxLen = 99;
topPtr = -1;
};
public void push (int num) {…};
public void pop () {…};
public int top () {…};
public boolean empty () {…};
}
Language Examples: C#
•Based on C++ and Java
83
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
C# Property Example
public class Weather {
public int DegreeDays { //** DegreeDays is a property
get {return degreeDays;}
set {
if(value < 0 || value > 30)
Console.WriteLine(
"Value is out of range: {0}", value);
else degreeDays = value;}
}
private int degreeDays;
...
}
...
Weather w = new Weather();
int degreeDaysToday, oldDegreeDays;
...
w.DegreeDays = degreeDaysToday;
...
oldDegreeDays = w.DegreeDays;
•Parameterized ADTs allow designing an ADT that can store any type elements
(among other things)
•Also known as generic classes
84
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs
Parameterized ADTs in Ada
generic
Max_Size: Positive;
type Elem_Type is private;
package Generic_Stack is
Type Stack_Type is limited private;
function Top(Stk: in out StackType) return Elem_type;
…
end Generic_Stack;
stack stk(100);
Parameterized ADTs in C++ (continued)
•The concept of ADTs and their use in program design was a milestone in the
development of languages
•Two primary features of ADTs are the packaging of data with their
associated operations and information hiding
87
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Everything is an object
–Advantage - elegance and purity
–Disadvantage - slow operations on simple objects
•Add objects to a complete typing system
–Advantage - fast operations on simple objects
–Disadvantage - results in a confusing type system (two kinds of entities)
•Include an imperative-style typing system for primitives but make everything
else objects
–If a derived class is-a parent class, then objects of the derived class must
behave the same as the parent class object
•A derived class is a subtype if it has an is-a relationship with its parent class
–Subclass can only add variables and methods and override inherited
methods in ―compatible‖ ways
–Can the new class be nested inside the class that uses it?
90
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
–In some cases, the new class is nested inside a subprogram rather than
directly in another class
•Other issues:
–Which facilities of the nesting class should be visible to the nested class and
vice versa
–The only type checking in Smalltalk is dynamic and the only type error
occurs when a message is sent to an object that has no matching method
–Private derivation - inherited public and protected members are private in the
subclasses
–Public derivation public and protected members are also public and
protected in subclasses
Inheritance Example in C++
class base_class {
private:
int a;
float x;
protected:
int b;
float y;
public:
int c;
float z;
};
•Because of its close relationship to C++, focus is on the differences from that
language
•General Characteristics
–All data are objects except the primitive types
–All primitive types have wrapper classes that store one data value
–All objects are heap-dynamic, are referenced through reference variables, and
most are allocated with new
–Static binding is also used if the methods is static or private both of which
disallow overriding
Support for OOP in Java (continued)
•Several varieties of nested classes
•All are hidden from all classes in their package, except for the nesting class
•Nested classes can be anonymous
•A local nested class is defined in a method of its nesting class
–No access specifier is used
Support for OOP in Java (continued)
•Evaluation
–Design decisions to support OOP are similar to C++
–No support for procedural programming
–No parentless classes
–Dynamic binding is used as ―normal‖ way to bind method calls to method
definitions
95
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
–The parent class version can still be called explicitly with the prefix base:
base.Draw()
–All C# classes are ultimately derived from a single root class, Object
Support for OOP in C# (continued)
•Nested Classes
–A C# class that is directly nested in a nesting class behaves like a Java static
nested class
–C# does not support nested classes that behave like the non-static classes of
96
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
–Efficient
Dynamic Binding of Methods Calls
•Methods in a class that are statically bound need not be involved in the CIR;
methods that will be dynamically bound must have entries in the CIR
Concurrency Introduction
• Concurrency can occur at four levels:
– Unit level
– Program level
• Because there are no language issues in instruction- and program-level
concurrency, they are not addressed here
Multiprocessor Architectures
Categories of Concurrency
• A thread of control in a program is the sequence of program points reached
as control flows through the program
• Categories of Concurrency:
Task Synchronization
• A mechanism that controls the order in which tasks execute
• Two kinds of synchronization
– Cooperation synchronization
– Competition synchronization
• Task communication is necessary for synchronization, provided by:
- Shared nonlocal variables
- Parameters
- Message passing
Kinds of synchronization
• Cooperation: Task A must wait for task B to complete some specific activity
before task A can continue its execution, e.g., the producer-consumer
problem
101
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• Competition: Two or more tasks must use some resource that cannot be
simultaneously used, e.g., a shared counter
Scheduler
• Providing synchronization requires a mechanism for delaying task
execution
• Task execution control is maintained by a program called the scheduler,
which maps task execution onto available processors
Semaphores
• Dijkstra - 1965
• Semaphores have only two operations, wait and release (originally called P
and V by Dijkstra)
– If there are no values in the buffer, the caller must be placed in the
queue of fullspots
Evaluation of Semaphores
• Misuse of semaphores can cause failures in cooperation synchronization,
e.g., the buffer will overflow if the wait of fullspots is left out
• Misuse of semaphores can cause failures in competition synchronization,
e.g., the program will deadlock if the release of access is left out
Monitors
• Ada, Java, C#
• The idea: encapsulate the shared data and its operations to restrict access
• A monitor is an abstract data type for shared data
Competition Synchronization
• Shared data is resident in the monitor (rather than in the client units)
• All access resident in the monitor
Cooperation Synchronization
• Cooperation between processes is still a programming task
106
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Evaluation of Monitors
• A better way to provide competition synchronization than are semaphores
• Semaphores can be used to implement monitors
• Monitors can be used to implement semaphores
• Support for cooperation synchronization is very similar as with
semaphores, so it has the same problems
Message Passing
• Message passing is a general model for concurrency
– Ada tasks have specification and body parts, like packages; the spec
has the interface, which is the collection of entry points:
task Task_Example is
entry ENTRY_1 (Item : in Integer);
end Task_Example;
Task Body
• The body task describes the action that takes place when a rendezvous
occurs
• A task that sends a message is suspended while waiting for the message to
be accepted and during the rendezvous
• Entry points in the spec are described with accept clauses in the body
accept entry_name (formal parameters) do
…
end entry_name
– Note: A sender must know the entry name of the receiver, but not
vice versa (asymmetric)
– The task body has an accept clause for each entry clause, placed in a
select clause, which is in a loop
• Extended accept clause - code following the clause, but before the next
clause
task Gas_Station_Attendant is
entry Service_Island (Car : Car_Type);
entry Garage (Car : Car_Type);
111
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
– Only one accept clause in a task can be active at any given time
Task Termination
• The execution of a task is completed if control has reached the end of its
code body
• If a task has created no dependent tasks and is completed, it is terminated
• If a task has created dependent tasks and is completed, it is not
terminated until all its dependent tasks are terminated
Binary Semaphores
task Binary_Semaphore is
entry Wait;
entry release;
end Binary_Semaphore;
Concurrency in Ada 95
• Ada 95 includes Ada 83 features for concurrency, plus two new features
– Asynchronous communication
Asynchronous Communication
• Provided through asynchronous select structures
• An asynchronous select has two triggering alternatives, an entry clause or
a delay
Java Threads
114
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
– The sleep method can be used by the caller of the method to block
the thread
– The join method is used to force a method to delay its execution until
the run method of another thread has completed its execution
Thread Priorities
• A thread‘s default priority is the same as the thread that create it
• The above two methods are synchronized which prevents them from
interfering with each other
– All 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
115
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
• The notify method is called to tell one waiting thread that the event it was
waiting has happened
• The notifyAll method awakens all of the threads on the object‘s wait list
C# Threads
– A thread can be made to wait for another thread to finish with Join
Synchronizing Threads
• An advance over Java threads, e.g., any method can run its own thread
• Thread termination is cleaner than in Java
• Synchronization is more sophisticated
Statement-Level Concurrency
• Objective: Provide a mechanism that the programmer can use to inform
compiler of ways it can map the program onto multiprocessor architecture
• Minimize communication among processors and the memories of the other
processors
High-Performance Fortran
• A collection of extensions that allow the programmer to provide
information to the compiler to help it optimize code for multiprocessor
computers
• Specify the number of processors, the distribution of data over the
memories of those processors, and the alignment of data
Summary
118
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
UNIT-VII
Exception Handling
Topics
•Introduction to Exception Handling
•Exception Handling in Ada
•Exception Handling in C++
•Exception Handling in Java
•Functional Programming Language Introduction
•Mathematical Functions
•Fundamentals of Functional Programming Languages
•The First Functional Programming Language: LISP
• ML
•Haskell
•Applications of Functional Languages
•Comparison of Functional and Imperative Languages
Basic Concepts
•Alternatives:
–Send an auxiliary parameter or use the return value to indicate the
return status of a subprogram
–
Pass an exception handling subprogram to all subprograms
Advantages of Built-in Exception Handling
•Error detection code is tedious to write and it clutters the program
•Exception handling encourages programmers to consider many different
possible errors
•Exception propagation allows a high level of reuse of exception handling code
Design Issues
•How are user-defined exceptions specified?
•Should there be default exception handlers for programs that do not provide
their own?
•Can built-in exceptions be explicitly raised?
•Are hardware-detectable errors treated as exceptions that can be handled?
•Are there any built-in exceptions?
•How can exceptions be disabled, if at all?
•How and where are exception handlers specified and what is their scope?
•How is an exception occurrence bound to an exception handler?
•Can information about the exception be passed to the handler?
120
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Handler form:
when exception_choice{|exception_choice} => statement_sequence
...
[when others =>
statement_sequence]
exception_choice form:
exception_name | others
•Handlers are placed at the end of the block or unit in which they occur
Binding Exceptions to Handlers
•If the block or unit in which an exception is raised does not have a handler
121
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Continuation
•The block or unit that raises an exception but does not handle it is always
terminated (also any block or unit to which it is propagated that does not
handle it)
Predefined Exceptions
•CONSTRAINT_ERROR - index constraints, range constraints, etc.
•NUMERIC_ERROR - numeric operation cannot return a correct value
(overflow, division by zero, etc.)
• PROGRAM_ERROR - call to a subprogram whose body has not been
elaborated
•STORAGE_ERROR - system runs out of heap
•TASKING_ERROR - an error associated with tasks
Evaluation
•The Ada design for exception handling embodies the state-of-the-art in
122
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Throwing Exceptions
•Exceptions are all raised explicitly by the statement:
throw [expression];
•The brackets are metasymbols
•A throw without an operand can only appear in a handler; when it appears,
it simply re-raises the exception, which is then handled elsewhere
123
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Classes of Exceptions
Continuation
•If no handler is found (all the way to main), the program is terminated
•To ensure that all exceptions are caught, a handler can be included in any
try construct that catches all exceptions
•A method cannot declare more exceptions in its throws clause than the
method it overrides
•A method that calls a method that lists a particular checked exception in its
throws clause has three alternatives for dealing with that exception:
Example
•A try construct with a finally clause can be used outside exception handling
try {
for (index = 0; index < 100; index++) {
…
if (…) {
return;
} //** end of if
} //** end of try clause
finally {
…
} //** end of try construct
Assertions
126
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Two forms
–assert condition;
–assert condition: expression;
Evaluation
•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
Mathematical Functions
•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
127
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Lambda Expressions
•Lambda expressions describe nameless functions
•Lambda expressions are applied to parameter(s) by placing the parameter(s)
after the expression
e.g., ( (x) x * x * x)(2)
which evaluates to 8
Functional Forms
•A higher-order function, or functional form, is one that either takes functions
as parameters or yields a function as its result, or both
Function Composition
•A functional form that takes two functions as parameters and yields a
function whose value is the first actual parameter function applied to the
application of the second
Form: h f ° g
which means h (x) f ( g ( x))
For f (x) x + 2 and g (x) 3 * x,
h f ° g yields (3 * x)+ 2
Apply-to-all
•A functional form that takes a single function as a parameter and yields a list
of values obtained by applying the given function to each element of a list of
parameters
Form:
For h (x) x * x
( h, (2, 3, 4)) yields (4, 9, 16)
–In an imperative language, operations are done and the results are
stored in variables for later use
ML
•Uses type declarations, but also does type inferencing to determine the types
of undeclared variables
•It is strongly typed (whereas Scheme is essentially typeless) and has no type
coercions
129
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Lists
Literal lists are specified in brackets
[3, 5, 7]
[] is the empty list
CONS is the binary infix operator, ::
4 :: [3, 5, 7], which evaluates to [4, 3, 5, 7]
CAR is the unary operator hd
CDR is the unary operator tl
fun length([]) = 0
| length(h :: t) = 1 + length(t);
Haskell
fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n
sub n
| n < 10 = 0
| n > 100 = 2
| otherwise =1
square x = x * x
•Length: #
e.g., #directions is 4
•Catenation is with ++
131
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Factorial Revisited
product [] = 1
product (a:x) = a * product x
List Comprehension
•Set notation
•List of the squares of the first 20 positive integers: [n * n | n ← [1..20]]
•All of the factors of its given parameter:
factors n = [i | i ← [1..n div 2],
n mod i == 0]
Quicksort
sort [] = []
sort (a:x) =
sort [b | b ← x; b <= a] ++
[a] ++
sort [b | b ← x; b > a]
Lazy Evaluation
Member Revisited
132
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•However, this would only work if the parameter to squares was a perfect
square; if not, it will keep generating them forever. The following version will
always work:
member2 (m:x) n
| m < n = member2 x n
| m == n = True
| otherwise = False
–Inefficient execution
–Programs can automatically be made concurrent
Summary
•Java exceptions are similar to C++ exceptions except that a Java exception
must be a descendant of the Throwable class. Additionally Java includes a
finally clause
134
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Unit-VIII
Logic Programming Languages
Topics
•Introduction
•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
Introduction
•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
135
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
•Particular form of symbolic logic used for logic programming called predicate
calculus
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
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:
136
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
negation a not a
conjunction a b a and b
disjunction a b a or b
equivalence a b a is equivalent to b
implication a b a implies b
a b b implies a
Quantifiers
Name Example Meaning
Clausal Form
•Too many ways to state the same thing
•Use a standard form for propositions
•Clausal form:
–B1 B2 … Bn A1 A2 … Am
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
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
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 clauses
Overview of Logic Programming
•Declarative semantics
–There is a simple way to determine the meaning of each statement
–Simpler than the semantics of imperative languages
•Programming is nonprocedural
–Programs do not state now a result is to be computed, but rather the
form of the result
138
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Fact Statements
•Used for the hypotheses
•Headless Horn clauses
female(shelley).
male(bill).
father(bill, jake).
Rule Statements
•Used for the hypotheses
139
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Example Rules
ancestor(mary,shelley):- mother(mary,shelley).
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
man(fred)
•Conjunctive propositions and propositions with variables also legal goals
father(X,mike)
140
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Simple Arithmetic
•Prolog supports integer variables and integer arithmetic
•is operator: takes an arithmetic expression as right operand and variable as
left operand
141
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Trace
•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)
Example
likes(jake,chocolate).
likes(jake,apricots).
likes(darcie,licorice).
likes(darcie,apricots).
trace.
likes(jake,X),
likes(darcie,X).
List Structures
142
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
Append Example
append([], List, List).
append([Head | List_1], List_2, [Head | List_3]) :-
append (List_1, List_2, List_3).
Reverse Example
reverse([], []).
reverse([Head | Tail], List) :-
reverse (Tail, Result),
append (Result, [Head], List).
Deficiencies of Prolog
•Resolution order control
•The closed-world assumption
•The negation problem
•Intrinsic limitations
Applications of Logic Programming
•Relational database management systems
•Expert systems
•Natural language processing
Summary
•Symbolic logic provides basis for logic programming
•Logic programs should be nonprocedural
•Prolog statements are facts, rules, or goals
•Resolution is the primary activity of a Prolog interpreter
•Although there are a number of drawbacks with the current state of logic
143
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in
144
Smartzworld.com jntuworldupdates.org