1 chapter 8: overview of programming language paradigms outline imperative languages functional...

63
1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming Parallel Programming Algorithmic Foundations Hardware Virtual Machine Softwar e Applicati ons Social Issues

Upload: zachary-hamblett

Post on 02-Apr-2015

256 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

1

Chapter 8: Overview of Programming Language Paradigms

Outline Imperative Languages Functional Programming Logic Programming Object-oriented

Programming Parallel Programming

Algorithmic Foundations

Hardware

Virtual Machine

Software

Applications

Social Issues

Page 2: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

2

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. Yes: MAKE “x SUM THING “y 4 no explicit data movement 2. Yes: no store and load, jump to address instruction 3. Yes: LOGO programs are portable 4. Yes: 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

Page 3: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

3

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)

Page 4: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

4

Imperative Languages Example of imperative languages:

LOGO has imperative constructs (but is rather functional) Pascal Fortran C Cobol

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: 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

Page 5: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

5

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

Page 6: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

6

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

Page 7: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

7

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 numbersreal: real numberschar: 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)

Imperative Languages

Page 8: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

8

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;

Page 9: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

9

Imperative Languages Statements in Pascal:

variable := expression; Meaning:

Set the value of “variable” to “(arithmetic) expression”

Steps: 1. Evaluate expression 2. Copy the value to the memory location associated with

“variable” Examples:

B := 3; C := -12; A := A + 1; A := B + C; NetSalary := Income – Tax;

Recall: one such assignment corresponds to several assembly language instructions.

Page 10: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

10

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))

Page 11: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

11

Imperative Languages If-then-else statement

General formif(Boolean condition) then

S1else

S2; Example:

if(B < (A+C)) thenA := 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

Page 12: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

12

Imperative Languages Compound Statement

Form:begin

S1;

S2;…

SN;end;

Examplebegin

writeln(‘This is the first statement’);writeln(‘This is the second statement’);writeln(‘This is the third statement’);

end; Attention: semicolon after the “end”

Page 13: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

13

Imperative Languages While loops in Pascal

General form of a While-loopwhile(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 bodyend.

Page 14: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

14

Imperative Languagesprogram 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

beginsum := sum + number;readln(number);end;

writeln(‘The total is ‘, sum:5);end.

Page 15: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

15

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

Page 16: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

16

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

Page 17: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

17

Imperative Languages The Fortran program:123456

PROGRAM MAINC 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

Page 18: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

18

Imperative Languages About the program:

We did not need to declare SUM and NUMBER as integers WRITE(*,*):

1. * = to standard output screen 2. * = use standard format here print on a new line

READ(*,*): 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

Major difference to Pascal Gotos make programs unreadable!!!

WRITE(*,20): 20 is the label of the subsequent format instruction

FORMAT(…) ‘ ‘ means single-spacing between lines Formats output, I5 means 5 positions for the SUM

Page 19: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

19

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

Page 20: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

20

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

Page 21: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

21

Imperative Languages Here the structure of the adder (details are omitted to keep things

simple)

IDENTIFICATION DIVISION. Here e.g. name of program, authorENVIRONMENT DIVISION. Specify a file as input and the screen as outputDATA DIVISION. Specify how data are formattedPROCEDURE DIVISION. the actual program is in the procedure divisionBEGIN. 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 screenSTOP RUN.

Page 22: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

22

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)

Page 23: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

23

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); }

Page 24: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

24

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

Page 25: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

25

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

Page 26: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

26

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 somethingon 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 62. actual argument = 6 the result value is 123. actual argument = 3 the result value is 6

Because 3. is a repetition of 1., the same result is produced

Page 27: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

27

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)

Page 28: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

28

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

Page 29: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

29

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)

result: 18 (polynomial 4)

result: 32 (polynomial -1)

result: 2

Page 30: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

30

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!

Page 31: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

31

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)

Page 32: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

32

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

Page 33: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

33

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

Page 34: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

34

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

Page 35: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

35

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

Page 36: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

36

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

Page 37: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

37

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 definitione.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)

Page 38: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

38

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

Page 39: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

39

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!)

Page 40: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

40

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

Page 41: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

41

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 whole problem by using the solution of a sub-problem

Page 42: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

42

Insertion: Recursive Functions

Another example Fibonacci numbers: F1 = F2 = 1 Fn = Fn-1 + Fn-2 for n >= 2

A non-recursive algorithm (you need to know the formula!): Get N Print sqrt(5)/2*((1+sqrt(5))/2)n - sqrt(5)/2*((1-sqrt(5))/2)n

A recursive solution: Get N Print F(N) F(N):

If(N = 1 or N = 2) then1

ElseF(N-1) + F(N-2)

Often, like here, recursion consumes more resources, but recursive solutions are often simpler.

Page 43: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

43

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

Algorithmic Foundations

Hardware

Virtual Machine

Software

Applications

Social Issues

But now each chapter is a disk

Page 44: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

44

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

Page 45: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

45

Insertion: Recursive Functions

Example: Solution for 3 disks Move 1 to Target Move 2 to Auxiliary Move 1 to Auxiliary Move 3 to Target Move 1 to Initial Move 2 to Target Move 1 to Target

Initial Auxiliary Target

3

1

2

Page 46: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

46

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)

Page 47: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

47

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

Page 48: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

48

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 …

Page 49: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

49

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?

Page 50: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

50

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, …

Page 51: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

51

Logic Programming User interactions with the program:

User poses a query and Program tries to answer it

Examples: ?-before(lincoln, fdr). {this is a user query}

Yes. {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.

Page 52: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

52

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).

Page 53: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

53

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

Page 54: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

54

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.

Page 55: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

55

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

Page 56: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

56

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

Page 57: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

57

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() …

Page 58: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

58

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

Page 59: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

59

Object-oriented Programming

Attributes and functions may have access restrictions 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) Information Hiding (Encapsulation)

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” (sincethey are also persons)

Page 60: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

60

Object-oriented Programming Polymorphism

Operation can operate on different data types Mechanisms:

Overloading of operators +: for real, integers, … - : for real, integers, … … selection at compile time

Dynamic binding Selection of module at run-time

Source of failures: Dynamic binding Multiple inheritance

Page 61: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

61

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, …)

Page 62: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

62

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

Page 63: 1 Chapter 8: Overview of Programming Language Paradigms Outline Imperative Languages Functional Programming Logic Programming Object-oriented Programming

63

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