Chapter 8: Overview of Programming Language Paradigms Outline

advertisement
Chapter 8: Overview of Programming
Language Paradigms

Outline





Imperative Languages
Functional Programming
Logic Programming
Object-oriented
Programming
Parallel Programming
Social Issues
Applications
Software
Virtual Machine
Hardware
Algorithmic Foundations
1
Imperative Languages


From Chapter 7 we know that a HLL has following advantages when
compared to assembly language (or machine language):

1. Programmers need not to manage data movement

2. Programmers have a macroscopic view of tasks

3. Programs in HLL are portable (not machine specific)

4. Statements in a HLL are closer to standard English and usual notations
Consider LOGO:





1.
2.
3.
4.
Yes:
Yes:
Yes:
Yes:
MAKE “x SUM THING “y 4  no explicit data movement
no store and load, jump to address instruction
LOGO programs are portable
LOGO programs are far more descriptive than assembly/machine language
Thus, in fact LOGO is a “good” representative of a HLL when we restrict
ourselves to above four characteristics
2
Imperative Languages


However:

LOGO has one similarity to assembly language:
 The programmer still thinks of memory locations when treating data

How?: LOGO uses the notion of a “variable” in order to indirectly “speak”
of memory (in fact LOGO is rather functional but it uses variables too)

To be more clear: A variable is nothing but a memory location with a
name associated to it (not an address as in assembly language!).
The consequence is:



Any program is treating “named” memory but in a similar way the
machine does it internally, that is, instruction by instruction
The philosophy of instructing the processor to do something is partly clear
in a LOGO program
Any programming language that is based on such instruction
philosophy is called Imperative Language (or Procedural Language)
3
Imperative Languages

Example of imperative languages:








Last 4 languages have the same philosophy, namely, treating the program
as a sequence of (high-level) instructions that manipulate data stored in
named memory (or variables)
Hence: They are very similar as we shall see
We will look at these languages by means of the following example:




LOGO has imperative constructs (but is rather functional)
Pascal
Fortran
C
Cobol
A user types in nonnegative integers
The program reads them until a sentinel (negative) value is typed in
The program then displays the sum of read integers
This program will serve as comparison of the four languages
4
Imperative Languages


But before speaking about the program, you may be asking yourself
a) what is different in these languages, and b) why do we need
different but similar ones relying on the same philosophy?
1) Differences?





differences in syntax (rules of grammar!)
Rules of control flow; e.g. how an if-then-else or while loop statement is
represented
How modules are represented
 But once again all of them base on the step-by-step way of problem
solving and the notion of a variable
2) Do we need all of them?


Strictly speaking no, BUT that was an evolution…
Also, each of these languages was designed for a special application
domain
5
Imperative Languages
Examples: Pascal  Teaching
Fortran  Numerical applications
Cobol  Databases
C
 Operating systems
Pascal was designed by N. Wirth (ETH Zurich, Switzerland) in the 1970s with the
aim of teaching disciplined programming
A Pascal name can be any combination of letters and digits as long as it starts with
a letter
Some reserved words are not allowed as names
Constant values can be given names:
const Pi = 3.14
Changeable values are called variables and they can be named:
var Radius: real;
Since binary numbers may be interpreted as positive whole numbers, signed
numbers, letters, or real numbers, Pascal enforces the programmer to declare the
type of each variable







6
Imperative Languages




Suppose we declare two variables:
var
Number: integer;
Letter: char;
Pascal will not allow us to add Letter to Number (since it does not make
sense)
 Our program will be more reliable than in assembly language, where such
errors cannot be intercepted.
Data types in Pascal:
integer: whole numbers
real: real numbers
char: letters
Words like var, integer, char, const and so on are reserved words
const Pi = 3.14

Pi:
.DATA 3.14
(in Pascal)
(in assembly language)
7
Imperative Languages

Input-output statements:



Recall in our Pseudo language, we wrote for example:
Get values of Radius
Written in Pascal this would be:
readln(Radius);
Correspondingly, for:
Print value of Surface
In Pascal:
writeln(Surface);
Better:
writeln(‘The surface is ‘, Surface);
Print a new (empty) line:
writeln;
8
Imperative Languages



Statements in Pascal:
variable := expression;
Meaning:
Set the value of “variable” to “(arithmetic) expression”
Steps:



Examples:



1. Evaluate expression
2. Copy the value to the memory location associated with “variable”
B := 3;
A := B + C;
C := -12;
A := A + 1;
NetSalary := Income – Tax;
Recall: one such assignment corresponds to several assembly
language instructions.
9
Imperative Languages

Boolean conditions:




An expression that evaluates to “true” or “false”
Examples:
A=0
(is A equal zero?)
 B < (A+C)
(is the values of B less than the sum of the
values of A and C?)
 A <> B
(is the value of A not equal the value of B?)
Comparison need not be numeric, example for use of char:
Initial := ‘D’;
Initial = ‘F’ (false)
Initial < ‘P’; (true)
Use of AND and OR is allowed:
(A = 0) or (B < (A+C))
10
Imperative Languages

If-then-else statement


General form
if(Boolean condition) then
S1
else
S2;
Example:
if(B < (A+C)) then
A := 2*A
else
A := 3*A;
Suppose:
Before: B = 2, A = 2, C = 3  After: B = 2, A = 4, C = 3
Before: B = 6, A = 2, C = 3  After: B = 6, A = 6, C = 3
11
Imperative Languages

Compound Statement

Form:
begin
S1;
S2;
…
SN;
end;

Example
begin
writeln(‘This is the first statement’);
writeln(‘This is the second statement’);
writeln(‘This is the third statement’);
end;

Attention: semicolon after the “end”
12
Imperative Languages





While loops in Pascal

General form of a While-loop
while(Boolean condition) do
S1;
Example: while (c > 0) do c := c –1;
Also functions/procedures are allowed in Pascal
Comments between curly braces  { comment }
Structure of a Pascal program:
program “program name” (list of files)
constant declarations;
variable declarations;
procedure declarations;
begin
program body
end.
13
Imperative Languages
program adder(input, output) {adds positive integers and terminates with a negative one}
var number: integer; sum : integer;
begin
writeln(‘Enter a positive integer, terminate with a negative integer’);
sum := 0;
readln(number);
while(number >= 0) do
begin
sum := sum + number;
readln(number);
end;
writeln(‘The total is ‘, sum:5);
end.
14
Imperative Languages

Example of user session (after running the program “adder”):
Enter a positive integer, terminate with an negative integer’
89
116
0
43
-1234
The total is 248




NOW: let us use another language, FORTRAN, for the same program
FORTRAN = FORmula TRANslation
Introduced very early in the mid-1950s at IBM
First HLL in the world; intended for engineering purposes
15
Imperative Languages

Unlike Pascal, Fortran has the following rules:








Program instruction must be written between columns 7-72
First 6 columns used for special purposes
A ‘C’ in the first column indicates that the line is a comment
Columns 1-5 are used for statement numbers (“numeric” labels, like
assembly language!)
A positive integer value in column 6 indicates that the line is a
continuation of the precedent one
No punctuations separate statements (compare semicolon in Pascal)
because each line is a complete instruction unless denoted by the 6-th
column of the next line
Variable names have at most 6 characters, all uppercase letters or digits
but always beginning with an uppercase letter
Numerical variables do not need to be declared; defaults are I, J, K, L, M,
and N for integers and other names for real variables
16
Imperative Languages

The Fortran program:
123456
C
PROGRAM MAIN
adds positive integers and terminates with a negative one
INTEGER SUM, NUMBER
WRITE(*,*) ‘Enter a positive integer, terminate with a negative one’
SUM = 0
READ(*,*) NUMBER
10 IF (NUMBER .GE. 0)THEN
SUM = SUM + NUMBER
READ(*,*) NUMBER
GO TO 10
ENDIF
WRITE(*,20) SUM
20 FORMAT(‘ ‘, ‘The Total is ‘, I5)
END
17
Imperative Languages

About the program:


We did not need to declare SUM and NUMBER as integers
WRITE(*,*):



READ(*,*):





Major difference to Pascal
Gotos make programs unreadable!!!
WRITE(*,20):


1. * = from standard input  keyboard
2. * = free formatting
.GE. = greater or equal (new Fortran compilers allow >=,<=, …)
GO TO: does the work of a while loop


1. * = to standard output  screen
2. * = use standard format  here print on a new line
20 is the label of the subsequent format instruction
FORMAT(…)


‘ ‘ means single-spacing between lines
Formats output, I5 means 5 positions for the SUM
18
Imperative Languages


Fortran is still in use
 Because of new versions
 Because there is a wealth of programmed functions in Fortran, which
are well-tested and thus highly reliable
  Reuse of code (is it old?)
Cobol



Cobol = COmmon Business-Oriented Language
Introduced in 1959-1960
Designed for processing files:




Master file: e.g. inventory file containing names and quantities of items available
Transaction files: e.g. containing names and quantities sold
 Master file should be updated (using information of transaction file) e.g. on
weekly basis and a summary report would be printed.
Cobol is less formal than Pascal/Fortran:

SUM = A+B reads in Cobol: ADD A TO B GIVING SUM
19
Imperative Languages






Like with FORTRAN there is now a large amount of applications
programmed in Cobol
Cobol is more adept at handling file input than keyboard input
For example, the data to be added should be prepared in a file (prior
to running the program). This also unburdens the user from entering
the same or almost the same data when running the program more
than one time
In Cobol columns 1-6 are reserved for line numbers
Column 7 may indicate that the line is a comment
A period marks the end of a sentence, which is a group of one or more
statements
20
Imperative Languages

Here the structure of the adder (details are omitted to keep things simple)
IDENTIFICATION DIVISION.
 Here e.g. name of program, author
ENVIRONMENT DIVISION.
 Specify a file as input and the screen as output
DATA DIVISION.
 Specify how data are formatted
PROCEDURE DIVISION.
 the actual program is in the procedure division
BEGIN. OPEN INPUT INPUT-DATA, OUTPUT OUTPUT-DATA.
READ-IT.
 Read next number in the file and print it on the screen if >= 0 and
GO TO E-O-J if the number is negative
E-O-J.
 End of job paragraph
 Write the cumulative sum on the screen
STOP RUN.
21
Imperative Languages

The C programming language



Emerged in the early 1970s
HLL but with hardware-oriented constructs
Why?

Because C was designed for systems programming





The operating system Unix was written in C (now other OSs too)
Because sometimes efficiency counts more than readability
In fact, when using C you can be almost as efficient as the underlying
hardware, but in the same time you can use powerful HLL abstractions, such
modules (in C called functions).
C is now one of the most used programming languages
Compared to Pascal, Fortran, and Cobol, C is rather similar to Pascal




Liberal use of columns
Liberal use of variable names
Compact code
No Gotos are needed (because while can be used)
22
Imperative Languages

Adder program in C:
/* This a comment, the program adds positive integers
until a negative one is typed in */
#include <stdio.h> /* always include this when using input and output */
main()
{ /* ‘{‘ is like begin of Pascal; ‘}’ is like end of Pascal */
int number, sum;
sum = 0;
printf(“Enter a positive number, terminate with a negative one\n”); /* like writeln of Pascal */
scanf(“%d”, &number); /* &number means address of the variable number */
while(number >= 0) {
sum = sum + number;
scanf(“%d”, &number); /* like readln of Pascal */
}
printf(“The total is %5d“, sum);
}
23
Imperative Languages

A final word:




The family of imperative languages includes C, Pascal, Fortran, Cobol,
and others not mentioned here
The main characteristic of these languages is the use of a step-by-step
instruction sequence to solve a problem
All of them use the notion of variables (for memory locations) and
programs directly manipulate variables in order to get final results
Similarities
 Fortran rather similar to Cobol (Gotos, column numbering, …)
 Pascal rather similar to C (no Gotos, while loops, liberal spacing…)
 No wonder:
 Fortran and Cobol rather old programming languages
 Pascal and C are (relatively) newer ones
24
Functional Programming







Functional programming:
A program is a combination of transformations on items. The
paradigm abstracts from variables, memory, and instructions.
A real functional programming language is LISP
LISP = LISt Processing
Designed 1958 at MIT
Second to FORTRAN in longevity:
FP (Functional Programming) is also another functional
programming language designed in 1977 (by designers of
Fortran)
Here we will use examples based on Scheme (a Lisp dialect)
Recall: LOGO is also similar to Lisp
25
Functional Programming

Functional programming paradigm:

Everything is a function (or each computing task is a function)

Function (like e.g. in C):
A mathematical recipe for taking argument(s) and doing something
on them, and delivering a result

Formally: f(arg1, arg2, arg3, …) is a function iff f transforms actual
values of arg1, arg2, arg3, … into a corresponding result (value) using
some specified rules

Different values of args may produce different results

BUT: same values of args always produce same results

Example: f(x) = 2*x
1. actual argument = 3  the result value is 6
2. actual argument = 6  the result value is 12
3. actual argument = 3  the result value is 6
Because 3. is a repetition of 1., the same result is produced
26
Functional Programming







In the broad sense:
A functions transforms a set of input data into a set of output data
In a functional programming language certain functions, called
primitives, are predefined (in libraries)
Compare: printf, scanf of C: These are predefined functions
Programmers can also defines own functions:
(define (double x)
(* 2 x))
“define”: indicates that some new function is being defined
The function name (here double) and its arguments (here x) follow
in parentheses
After defining a function, we can invoke it by providing its name
and a list of argument values (here only one for the x)
27
Functional Programming

Examples of functions invocations:



(double 4)
Result is: 2*4 = 8
(double 6)
Result is: 2*6 = 12
Another function:



(define (square x)
(* x x))
“square” multiplies its argument value by itself
Examples
 (square 3)  results is: 9
 (square 8)  results is: 64
28
Functional Programming




We can use already defined functions in order to defines new
ones
Example:
(define (polynomial x)
(double (square x)))
Mathematically: f(x) = 2.x2
Sample invocations with actual arguments

(polynomial 3)


(polynomial 4)


 result: 18
 result: 32
(polynomial -1)

 result: 2
29
Functional Programming

Computations steps for (polynomial x): ( hidden now!!!)




1. Evaluate the value of x (including accessing memory)
2. Compute the value of (square x) and store the result in r (memory!)
3. Compute the values of (double r) and get the final result
Attention:




These steps are given in order to understand how the computer actually
performs the computation
These steps are hidden for the programmer
The programmer does not think in terms of evaluation steps and of
memory
For the programmer: “polynomial” is a black box that gives a result
when invoked using actual input values; it is a “real” function!
30
Functional Programming

Observe that “polynomial” uses two other functions:






“square”
“double”
In functional programming languages complex functions can be
built by applying the results of other functions, which may also
apply the results of still other ones, and so on
 functional languages are also called applicative languages
Lisp processes lists of arguments (recall Lisp = LISt Processing)
No arguments means an empty list of arguments, called nil
Primitive list processing functions in Scheme:


list: creates a list of argument
Example
(list 2 3 4)  creates the list (2 3 4)
31
Functional Programming



car: pronounced as in automobile
 car takes a nonempty list as argument and returns the first
element of the list as a result
 Note: the result of car is not always a list!!!
 Example
(car (list 2 3 4))  returns 2
cdr: pronounced could-er
 cdr takes a nonempty list as argument and returns as a result the
list that remains after the first element of the list has been
removed
 Note: the result of cdr is always a list!!!
 Example
(cdr (list 2 3 4))  returns (3 4)
As a special case: if the list has only one element cdr returns nil
 (cdr (list 6))  returns nil
32
Functional Programming



null?:
 When applied on a list it returns true if the list is nil and false
otherwise
 Examples:
 (null? Nil)  result: true
 (null? (2 4 5))  result: false
With the four primitives (list, car, crd, and null?) we can now
write our old adder program in Lisp
Rather than using a sentinel value in order to mark end of the
list of values to be added, a user only types for example:
(adder (list 3 4 5))

This would produce the result (the sum): 3+4+5 = 12
33
Functional Programming

Adder program in Lisp:
(define (adder input-list)
(cond ((null? input-list) 0)
(else (+ (car input-list) (adder (crd input-list)))))

Some remarks about the program:





Adder is a function
It has one argument named input-list
When we invoke it using (adder (list 3 4 5)) the input-list actual
value becomes (3 4 5)
cond (conditional) is like if in Pascal or C
Observe:
 no loop has been used
 Every thing acts a function
34
Functional Programming

Now: how does this program work?


Assume user types in: (adder (list 3 4 5))
Then following steps are performed:
 1. input-list = (3 4 5)
 2. (null? (3 4 5))  false
 3. Else execution:
 3.1 (car (3 4 5)) returns 3, which is added to a second
quantity
 3.2 The second quantity is the result of invoking the adder
function on the argument (cdr (3 4 5)), which is (4 5)
 3.3 Hence the result so far is: 3 + (adder (list 4 5))
 4. Now the program invokes itself again in order to compute
the remaining (smaller) part (adder (list 4 5)), thus returning
to step 1 with new value for the input-list
35
Functional Programming









5. Once again a test null? is done on the list (4 5)  false
6. Thus, so far results is: 3 + 4 + (adder (5))
7. Adder function calls itself another time using (5) as input-list
8. Null?  false
9. Result is so far: 3 + 4 + 5 + (adder nil)
10. Last time adder is called using nil as input-list
11. Null?  delivers true this time (since input-list = nil)
12. Thus, final result is 3 + 4 + 5 + 0 = 12
All of these steps are done automatically, after typing (adder
(list 3 4 5)), the user will instantly see the result: 12
36
Functional Programming




The computation steps at a glance:
(adder (3 4 5)) =
3 + (adder (4 5)) =
3 + 4 + (adder (5)) =
3 + 4 + 5 + (adder nil) =
3 + 4 + 5 + 0 = 12
The adder function definition involves itself again, but acting on a
shorter list
 Recursion
Recursive function:
A function that uses itself in its definition
e.g. adder uses adder
A way to ensure termination of a recursive function f is to require that
any call of f should operate on a smaller input data set (e.g. adder
operates on a shorter list)
37
Functional Programming

What is the beauty of functional programming:






You think mathematically: everything is a function
You need not know where temporary values and results are stored
Your program can be very complex but still compact and
understandable
Your program is better suited to be verified using a specification
(correctness proofs)
No side effects are possible, which enhance reliability
Questionable is efficiency:



Always calling new functions takes time
Function implementations need a lot of memory space
However: for prototyping these questions are not primary ones
38
Insertion: Recursive Functions





Recursion is a fundamental way of problem solving in computer science
In fact, not only Lisp but almost all programming languages (including
Pascal, C, Fortran 90) support recursion
Recursion is eminently useful, because it simplifies problem solving
tremendously
Recursion is a property of an algorithm, thus, we can treat it without
referring to a special programming language, or say you can write
recursive algorithms using Pseudo-Code, if we extend it by function
definitions
Recursion is often used in real life:



Reading a book may be defined as reading the first page followed by
reading the rest of the book (the rest of … = a shorter step!)
Climbing a ladder can be defined as climbing the first rung followed by
climbing the rest of the ladder (a shorter step!)
Driving an amount of miles can be defined as driving one mile and then
driving the rest of the distance (a shorter distance!)
39
Insertion: Recursive Functions


How to use recursion at the Pseudo-Code level:

Give your algorithm a name and some arguments, the arguments
specify the initial problem to solve (that is, the whole problem)

In some steps of the algorithm apply your algorithm (by using its name)
on different arguments that specify some sub-problem
Example: computing the factorial N (the product N*(N-1)*…*2*1)

First, here a non-recursive version
 Get N
 Set fac to 1
 Set I to 1
 While I <= N
 Set fac to fac*I
 Increment I
 Print fac
40
Insertion: Recursive Functions
Now, the recursive version of factorial:

1. Get N

2. Print fac(N)

fac(N):
1. if(N = 1) then
2.
1
else
3.
n*fac(N-1)
Remarks:

Step 1/2: solves the simplest case (N=1)

Step 3: solves the general case by combining a multiplication and a
recursive call of the algorithm using a new input argument (N-1); in
order words, the problem fac(N) is now broken down to the simpler
problem fac(N-1)
This simple example shows how recursion really simplifies a solution of a
41
whole problem by using the solution of a sub-problem



Insertion: Recursive Functions


Another example Fibonacci numbers:
 F1 = F 2 = 1
 Fn = Fn-1 + Fn-2 for n >= 2
A non-recursive algorithm (you need to know the formula!):



A recursive solution:




Get N
Print sqrt(5)/2*((1+sqrt(5))/2)n - sqrt(5)/2*((1-sqrt(5))/2)n
Get N
Print F(N)
F(N):
 If(N = 1 or N = 2) then
1
 Else
F(N-1) + F(N-2)
Often, like here, recursion consumes more resources, but recursive
42
solutions are often simpler.
Insertion: Recursive Functions


A last (but a nice) example using recursion
Towers of Hanoi:

A number of disks of decreasing diameter are put the one on the other

Like our lecture stuff 
Social Issues
Applications
Software
Virtual Machine
Hardware
Algorithmic Foundations

But now each chapter is a disk
43
Insertion: Recursive Functions

The Hanoi Problem:

Given:



3 different places called: Initial, Target, and Auxiliary AND
A tower of N disks in place Initial
Goal:

Move the tower of disks from Initial to Target using the following 2
rules:
 Only one disk may be moved at a time and this disk must be the top
disk on a tower
 A larger disk can never be placed on top of a smaller one
Initial
Auxiliary
Target
44
Insertion: Recursive Functions

Example: Solution for 3 disks







Move
Move
Move
Move
Move
Move
Move
1
2
1
3
1
2
1
to
to
to
to
to
to
to
Target
Auxiliary
Auxiliary
Target
Initial
Target
Target
1
2
3
Initial
Auxiliary
Target
45
Insertion: Recursive Functions




But how about a general solution, that is, for an arbitrary N?
You may get mad when moving without a general scheme …
However: Recursion helps here !!!
Idea of recursive solution:





Move N-1 disks from Initial to Auxiliary
Move disk N from Initial to Target
Move N-1 disks from Auxiliary to Target
Thus, we decompose the problem into 3 steps, each step adheres to the
moving rules.
Now the algorithm is easy (we use 1=Initial, 2=Auxiliary, 3=Target):


Get N
HanoiMove(N, 1, 2, 3)
46
Insertion: Recursive Functions


HanoiMove(N, i, a, t):

if(N = 1)
 Print “Move N from i to t”

else
 HanoiMove(N-1, i, t, a)
 Print “Move N from i to t”
 HanoiMove(N-1, a, i, t)
Tracing the algorithm:

1 Disk: N = 1  HanoiMove(1, 1, 2, 3)
 Prints: Move 1 from 1 to 3

2 Disks: N = 2  HanoiMove(2, 1, 2, 3)
 HanoiMove(1, 1, 3, 2)  Prints: Move 1 from 1 to 2
 Move 2 from 1 to 3 (printed by this call)
 HanoiMove(1, 2, 1, 3)  Prints: Move 1 from 2 to 3
47
Logic Programming


Functional programming has the goal of letting the programmer
think about a (virtual) machine that understands functions and
operates on them. (no memory, no instructions, etc.)
Logic programming goes a step further:




The programmer should only know facts about a special domain AND
Provide rules of how new facts can be deduced
When a user poses a query (question) to the computer, the latter
begins with a fact storehouse and attempts to apply a logical
deduction to answer the user query
Domains of interests are those where the use of facts makes sense
e.g.:




Medicine
Literature
Chemistry
…
48
Logic Programming

Logic has been used successfully to write expert systems





A “human” expert in a special domain provides facts and rules,
based on his/her experience and knowledge
A logic program can make inferences that are “close” (?) to what
the human expert would make
Best representative of a logic programming language is Prolog
Prolog = PROgramming in LOGic
Facts in Prolog


Express a property about a single object or a relationship among
several ones
Example: Domain: US History

Which president was in office during what known event?
49
Logic Programming

Prolog facts:
president(lincoln, gettysburg_address).
president(lincoln, civil_war).
president(nixon, first_moon_landing).
president(jefferson, lewis_and_clack).
president(kennedy, cuban_missile_crisis).
before(jefferson, lincoln).
before(lincoln, fdr).
before(fdr, kennedy).
before(kennedy, nixon).

That was a prolog program !!!


Only a list of facts
No Gotos, whiles, memory references, …
50
Logic Programming


User interactions with the program:
 User poses a query and
 Program tries to answer it
Examples:

?-before(lincoln, fdr).


Yes.
{this is a user query}
{this is the Prolog answer}
Prolog asks after a response:
More? (Y/N):
If there are no matching facts, Prolog will print:
No.

?-president(lincoln, civil_war).


Yes.
?-president(truman, world_war_II).

No.
51
Logic Programming




More complicated queries can be phrased
A comma means an AND
To query facts A and B, the user writes A, B
Example:

?-president(lincoln, civil_war), before(lincoln, fdr).


Yes.
So far, only retrieval from a fact database but Prolog can do more!
 Use of variables



Attention: Do not confuse Prolog variables with variables of Pascal, C, and
so on (memory aspect is hidden in Prolog)
Prolog variables are templates and they must begin with uppercase letters
Example:



?-president(lincoln, X).
This is to say give ANY known event during the office period of lincoln
Or in other words: ?-president(lincoln, Something).
52
Logic Programming


On the query ?-president(lincoln, X).
Prolog would answer:




X = gettysburg_address
X = civil_war
The query ?-before(lincoln, kennedy) would yields to No.
However, the facts:
before(lincoln, fdr).
before(fdr, kennedy).
Are part of the database ???

We have to tell Prolog, by means of a rule, that Lincoln
precedes Kennedy, even if the facts do not say that directly

 A new rule has to be added
53
Logic Programming




A Prolog rule behaves like an if-then statement
Its form is:
A :- B
This means if fact B is true, then fact A is also true
Now we can add a new rule for the “precedes” relation:
precedes(X, Y) :- before(X, Y).
precedes(X, Y) :- before(X, Z), precedes(Z, Y).


Observe this was a recursive rule!
Now we can ask Prolog:

?-precedes(fdr, kennedy).


Yes.
?-precedes(lincoln, nixon).

Yes.
54
Logic Programming

?-precedes(lincoln, X).





X = fdr
X = kennedy
X = nixon
We can add another rule to say when an event is earlier than
another one.
New rule:
earlier(X, Y) :- president(PX, X), president(PY, Y), precedes(PX, PY).


That is to say: the corresponding president should be earlier
We ask Prolog:

?-earlier(world_war_II, X)


X = first_moon_landing
X = cuban_missile_crisis
55
Object-oriented Programming




OOP is another paradigm: Everything is an object
Idea: simulate the real world where everything is an object that
has some properties and can perform some tasks (functions)
OOP does not aim directly to hide the step-by-step instruction
scheme (like in functional and logic programming), the idea is
rather to put instruction sequences in the right contexts and to
leverage more programmability, reliability, and reusability
Objects:



Have attributes and
Behavior
Can communicate among each other
56
Object-oriented Programming

Attributes:


Data related to an object
Exmaple: Object “Person” would have attributes like





Name
Birthday
Hobbies
…
Behavior:


Set of functions an object can perform
Example: “Person” has function like:





isWorking()
ReadText()
WriteText()
isAtHome()
…
57
Object-oriented Programming

Communication among objects:




Using the behavioral functions
Example: Person1 wants to know whether or not person2 is at home:
if(person2.isAtHome())
doSomething1
else
doSomething2
Example: Person1 wants to give something to read to person2:
person2.ReadText(“I am back from my journey …”);
Representatives of OO languages are:



C++
Java
Smalltalk
58
Object-oriented Programming

Attributes and functions may have access restrictions




Information Hiding (Encapsulation)



Public: for everyone to use
Protected: only some objects may use them (e.g. lower in the hierarchy)
Private: only the owner object can use them (not allowed for the public)
Private attributes/functions are not accessible from the outside
Public functions can be provided as interfaces. Access to private data is
controlled by the public functions
Inheritance:


Objects may inherit attributes/functions from other ones (“relatives”)
For example:
 Object “Student”
 Object “Teacher”
Both may inherit attributes/functions from object “Person” (since
they are also persons)
59
Object-oriented Programming

Polymorphism


Operation can operate on different data types
Mechanisms:

Overloading of operators





Dynamic binding


+: for real, integers, …
- : for real, integers, …
…
 selection at compile time
Selection of module at run-time
Source of failures:


Dynamic binding
Multiple inheritance
60
Parallel Programming



Parallel programming aims at reducing computation time
Like OOP parallel programming (PP) does not aim at hiding
step-by-step instruction processing
Rather, the Von-Neumann type style is changed in another way:


Computations are allowed to execute in parallel
Classes based on the architecture (see also Chapter 5):

SIMD


 Vector computers
MIMD

 Parallel computers (e.g. Intel iPSC, Transputers, …)
61
Parallel Programming

Example for SIMD:
V: private { V is private for each ALU (in ALU local memory) }
K: public { K is the global for all ALUs (in main memory) }
…
Parallel [1..5] { use 5 ALUs }
V = V + K; { done in each ALU }
End Parallel
 Example adds (K, K, K, K, K) to (V, V, V, V, V)

Exampl for MIMD:


Search a name in a 20, 000, 000-entry list
 use 100 processors
62
Parallel Programming


myList = List[1..200000]: private { for each processor a potion }
Name: public
…
Parallel [1..100] { use 100 processors }
SeqSearch(myList, Name, Interrupt)
If found then send interrupt
End Parallel
MIMD does not require that all processors do the same task:
Parallel
Processor 1: A = 1
Processor 2: Read(B)
Processor 3: Average(X, Y, Z)
End Parallel
63
Download