Programming Languages Shyh-Kang Jeng National Taiwan University Department of Electrical Engineering/

advertisement
Programming Languages
Shyh-Kang Jeng
Department of Electrical Engineering/
Graduate Institute of Communication Engineering
National Taiwan University
1
Generations of programming
languages
2
Machine Instructions and
Mnemonic Techniques
156C
166D
5056
306E
C000
LD R5, PRICE
LD R6, TAX
ADDI R0, R5 R6
ST R0, TOTAL
HLT
3
Assemblers and Assembly
Languages



Programs to translate other programs
written in mnemonic form into machine
compatible form
Assemble machine instructions out of the
op-codes and operands obtained by
translating mnemonics and identifiers
Mnemonic systems for representing
programs are recognized as programming
languages called assembly languages
4
Assembly Languages


Second-generation language
Machine dependent


Must conform to the machine’s register
configuration and instruction set
Low level primitives

A programmer is still forced to think in terms
of the small, incremental steps of the
machine’s language
5
Design Process of a Product


Better suited to the use of high-level
primitives, each representing a concept
associated with a major feature of the
product
Once the design is complete, the
primitives can be translated to lower-level
concepts relating to the details of
implementation
6
Third-Generation Languages



High-level primitives
Machine independent if standard is
followed
FORTRAN


COBOL


FORmula TRANslator
COmmon Business-Oriented Language
BASIC
7
Compilers vs. Interpreters

Compilers



Compile several machine instructions into
short sequences to simulate the activity
requested by a single high-level primitive
Produce a machine-language copy of a
program that would be executed later
Interpreters

Execute the instructions as they were
translated
8
Machine Independence and Beyond

Restrictions of the machines


Size of registers and memory cells
Dialects and standard languages



ANSI (American National Standards
Institute) standard
ISO (International Organization of
Standardization) standard
Language extensions
9
Evolution of Programming
Paradigms
10
Imperative Paradigm



Procedural paradigm
Develops a sequence of commands that
when followed, manipulate data to
produce the desired result
Approaches a problem by trying to find
an algorithm for solving it
11
Declarative Paradigm

Emphasizes




“What is the problem?”
Rather than “What algorithm is required to
solve the problem?”
Implemented a general problem-solving
algorithm
Develops a statement of the problem
compatible with the algorithm and then
applies the algorithm to solve it
12
Functional Paradigm



Views the process of program
development as connecting predefined
“black boxes,” each of which accepts
inputs and produces outputs
Mathematicians refer to such “boxes” as
functions
Constructs functions as nested complexes
of simpler functions
13
Functional Paradigm Example
14
Examples of LISP Expressions
(Find_diff
(Find_Sum Old_balance Credits)
(Find_Sum Debits))
(First (Sort List))
15
Advantages of Functional
Paradigm


Constructing complex software from
predefined primitive functions leads to
well-organized systems
Provides an environment in which
hierarchies of abstraction are easily
implemented, enabling new software to
be constructed from large predefined
components rather than from scratch
16
Object-Oriented Paradigm


OOP
Encapsulation of data and procedures





Lists and sorting
Graphic user interface (GUI)
Natural modular structure and program
reuse
Communication between modules is
accomplished by passing messages
CORBA and software components
17
Statements in Programming
Languages

Declarative statements


Imperative statements


Define customized terminology that is used
later in the program
Describe steps in the underlying algorithms
Comments

Enhance the readability of a program
18
Composition of a Typical Imperative
Program or Program Unit
19
Variables, Literals, Constants


EffectiveAlt  Altimeter + 645
Variables


Literals


Example: EffectiveAlt, Altimeter
Example: 645
Constants

Example: const int AirportAlt = 645;
20
Data Type

Refers to



Interpretation of data
Operations that can be performed on the data
Common types

integer, real, character, Boolean
21
Variable Declarations

Pascal
Length, width: real;
Price, Tax, Total: integer;

C, C++, Java, C#
float Length, width;
int Price, Tax, Total;

FORTRAN
REAL Length, Width
INTEGER Price, Tax, Total
22
Data Structure


Conceptual shape of data
Common data structure


Homogeneous array
Heterogeneous array
23
Declaration of a 2D Array

C
int Scores[2][9];

Java
int Scores[][]=new int [2][9];

Pascal
Scores: array[3..4, 12..20] of integer;
24
A two-dimensional array
25
Declaration of a Heterogeneous
Array

Pascal
var Employee : record
Name: packed array[1..8] of char;
Age: integer;
SkillRating: real;
end

C
struct Employee {
char Name[8];
int Age;
float SkillRating;
};
26
Assignment Statements and
Operators

C, C++, Java
Total = Price + Tax;

Ada, Pascal
Total := Price + Tax;

APL
Total <- Price + Tax;


Operator precedence
Operator overloading
27
Control Statements



Alter the execution sequence of the program
goto is the simplest control statement
Example
20
40
60
70
goto 40
if( Price < 50 ) then
Total = price + 10
Total = Price + 5
goto 70
else
if Price < 50 goto 60
Total = Price + 10
goto 20
endif
Total = Price + 5
stop
stop
28
Control Structure (1)
29
Control Structure (2)
30
Control Structures (3)
31
Comments


For inserting explanatory statements
(internal documentation)
C++ and Java
/* This is
a comment
*/
// This is a comment

Explain the program, not to repeat it

Example: Total = Price + Tax;
32
Procedures



A procedure is a set of instructions for
performing a task that can be used as an
abstract tool by other program units
Control is transferred to the procedure at the
time its services are required and then returned
to the original program unit (calling unit) after
the procedure is finished
The process of transferring control to a
procedure is often referred to as calling or
invoking the procedure
33
Procedures (1)
34
Procedures (2)




Local variables
Global variables
Procedure’s header
Parameters


Formal parameters
Actual parameters
35
A C Procedure
36
Pass by Value
5
5
5
6
5
37
Pass by Reference
5
6
6
38
Functions


A program unit similar to procedure unit
except that a value is transferred back
to the calling unit
Example
Cost = 2 * TotalCost( Price, TaxRate );
39
A C Function
40
Input/Output Statements



I/O statements are often not primitives
of programming languages
Most programming languages
implement I/O operations as procedures
or functions
Examples
printf( “%d %d\n”, value1,
value2 );
cout << value << endl;
41
A Formatted Output Example in C
42
Translation Process
43
Lexical Analyzer


Reads the source program symbol by
symbol, identifying which groups of
symbols represent single units, and
classifying those units
As each unit is classified, the lexical
analyzer generates a bit pattern known as
a token to represent the unit and hands
the token to the parser
44
Parsing





Group lexical units (tokens) into
statements
Identify the grammatical structure of
the program
Recognize the role of each component
Fixed-format vs. free-format languages
Key words and reserved words
45
Syntax Diagram


Pictorial representations of a program’s
grammatical structure
Nonterminals


Requires further description
Terminals
46
Syntax Diagram
47
Parse Tree



Pictorial form which represents a particular
string conforming to a set of syntax
diagrams
The process of parsing a program is
essentially that of constructing a parse
tree for the source program
A parse tree represents the parser’s
understanding of the programmer’s
grammatical composition
48
Parse Tree
49
Dangling else Problem


if B1
then ( if B2 then S1 )
else S2
if B1
then ( if B2 then S1
else S2 )
50
Parse Tree (1)
51
Parse Tree (2)
52
Mini Review

Draw the parse tree for the expression
x y  x  z
based on the given syntax diagrams
53
Answer
Expression

Term
Factor
x

Factor
y
Expression
Term
Factor

Expression
Term
Factor
x
z
54
Mini Review

Describe the strings that conforms to the
structure Chacha according to the following
syntax diagrams
Chacha
Step
Step
Chacha
Turn
forward
backward
backward
forward
Turn
swing
right
left
Cha
Cha Cha
Cha
Cha Cha
55
Other Translation Topics





Symbol tables
Coercion
Strongly typed language
Code generation
Code optimization


x  y + z;
w  x + z;
56
Object-Oriented Approach to the
Translation Process
57
Linker


Most programming environments allow the
modules of a program to be developed
and translated as individual units at
different times
Linker links several object programs,
operating system routines, and other
utility software to produce a complete,
executable program (load module) that is
in turn stored as a file in the mass storage
system
58
Loader



Places the load module in memory
Often part of the operating system’s
scheduler
Important in multitasking systems


Exact memory area available to the programs
is not known until it is time to execute it
Loader also makes any final adjustments that
might needed once the exact memory location
of the program is known (e.g. dealing with
the JUMP instruction)
59
Program Preparation Processes
60
Object-Oriented Programming


Objects and classes
Abstract data type


Example (in C++): LaserClass laser1, laser2;
Inheritance
Example (in Java):
class RechargeableLaser extends
LaserClass



Polymorphism
Encapsulation
61
A Class Example
62
Constructor
63
An Example for Encapsulation in
Java or C#
64
Concurrent Processing

True parallel processing



Requires multiple CPU’s
Ada task and Java thread
Basic actions


Creating new process
Handling communication between processes
Mutually exclusive access
 Critical region


A data item augmented with the ability to
control access to itself is called a monitor
65
Interaction between processes


Mutual exclusion = a method for
ensuring that data can be accessed by
only one process at a time
Monitor = a data item augmented with
the ability to control access to itself
66
Spawning processes
67
Additional Reading for Logical
Programming

S. Russell and P. Norvig, Artificial
Intelligence: A Modern Approach,
Englewood Cliffs, NJ: Prentice Hall, 1995
68
Logical Deduction




Either Kermit is on stage or Kermit is
sick
Kermit is not on stage
Kermit is sick
Resolution Principle
P OR Q
Q  P
Q
P
69
Truth Table
P
Q
P
PQ PQ P Q P Q
False
False
True
False
False
True
True
False
True
True
False
True
True
False
True
False
False
False
True
False
False
True
True
False
True
True
True
True
70
Implication
P  Q  P OR Q
U
P
Q
71
Resolving (P OR Q) and (R OR  Q)
to Produce (P OR R)
72
Clause Form


First-order predicate logic vs. Higherorder predicate logic
Clause form
( P1 OR Q1 ) AND( P2 OR Q2 ) AND AND( PN OR QN )
73
Confirming the Inconsistency of a
Set of Inconsistent Clauses
74
Interpretation (1)



P: Kermit is on stage
Q: Kermit has got SARS for two weeks
R: Kermit coughs
P OR Q  Q  P
R OR Q  R  Q
P OR R  R  P
75
Interpretation (2)
Q  P
R  Q
R
P
R  P
P
contradiction
76
Automatic Reasoning
using reduction ad absurdum




Want to confirm a collection of statements
implies the statement P
Same as contradicting the statement P
Apply resolution to the original statements
and the statement P until an empty clause
occurs
With P inconsistent with the original
statements, the original statements must
imply P
77
Unification

The process of assigning values to
variables so that resolution can be
performed
( Mary is at X )  ( Mary ' s lamb is at X )
Mary is at home
( Mary is at X )OR ( Mary ' s lamb is at X )
( Mary is at home)
( Mary is at home)OR ( Mary ' s lamb is at home)
( Mary is at home)
( Mary ' s lamb is at home)
78
Prolog (1)



PROgramming in LOGic
A Prolog program consists of a
collection of initial statements upon
which the underlying algorithm bases
its deductive reasoning
Predicate


A fact about its argument
Examples parent (bill , mary).
faster(turtle, snail ).
faster(rabbit , turtle).
79
Prolog (2)


Rule
faster( X , Z ) :  faster( X , Y ), faster(Y , Z ).
Goal

Proposed to the system and the system
applies the resolution to try to confirm that
the goal is a consequence of the initial
statements
80
Prolog Queries
faster(turtle, snail ).
faster(rabbit , turtle).
faster(rabbit , snail ).
faster(W , snail ).
faster(rabbit , W ).
faster(V , W ).
81
Exercise

2, 5, 8, 22, 28, 29, 31, 37, 49, 53
82
Download