programming paradigms

28
Programming Programming Paradigms Paradigms cs7100(Prasad) L6Pdm 1

Upload: karma

Post on 06-Jan-2016

64 views

Category:

Documents


4 download

DESCRIPTION

Programming Paradigms. Programming Paradigm. A way of conceptualizing what it means to perform computation and how tasks to be carried out on the computer should be structured and organized . Imperative : Machine-model based Functional : Equations ; Expression Evaluation - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programming Paradigms

Programming ParadigmsProgramming Paradigms

cs7100(Prasad) L6Pdm 1

Page 2: Programming Paradigms

Programming ParadigmProgramming Paradigm

A way of conceptualizing what it means to A way of conceptualizing what it means to perform computation and how tasks to be perform computation and how tasks to be carried out on the computer should be carried out on the computer should be structured and organized.structured and organized.

» Imperative : Imperative : Machine-model basedMachine-model based

» Functional : Functional : Equations; Expression EvaluationEquations; Expression Evaluation

» Logical : Logical : First-order Logic DeductionFirst-order Logic Deduction

» Object-Oriented : Object-Oriented : Programming with Data TypesProgramming with Data Types

cs7100(Prasad) L6Pdm 2

Page 3: Programming Paradigms

cs7100(Prasad) L6Pdm 3

Imperative vs Non-Imperative Imperative vs Non-Imperative

Functional/Logic programsFunctional/Logic programs specify specify WHAT WHAT is to be computed abstractly, leaving the is to be computed abstractly, leaving the details of data organization and instruction details of data organization and instruction sequencing to the interpreter. sequencing to the interpreter.

In constrast, In constrast, Imperative programsImperative programs describe describe

the details of the details of HOWHOW the results are to be the results are to be obtained, in terms of the underlying obtained, in terms of the underlying machine model.machine model.

Page 4: Programming Paradigms

cs7100(Prasad) L6Pdm 4

Illustrative ExampleIllustrative Example

Expression (to be computed) :Expression (to be computed) : a + b + c a + b + c Recipe for Computation:Recipe for Computation:

– Intermediate Code Intermediate Code » T := a + b; T := T + c;T := a + b; T := T + c;

– Accumulator MachineAccumulator Machine» Load a; Add b; Add cLoad a; Add b; Add c

– Stack MachineStack Machine» Push a; Push b; Add; Push c; AddPush a; Push b; Add; Push c; Add

Page 5: Programming Paradigms

cs7100(Prasad) L6Pdm 5

Imperative vs Non-ImperativeImperative vs Non-Imperative

Functional/Logic styleFunctional/Logic style clearly separates clearly separates WHAT WHAT aspects of a program aspects of a program (programmers’ responsibility) from the (programmers’ responsibility) from the HOWHOW aspects (implementation decisions). aspects (implementation decisions).

An An Imperative programImperative program contains both the contains both the specification and the implementation specification and the implementation details, inseparably inter-twined.details, inseparably inter-twined.

Page 6: Programming Paradigms

cs7100(Prasad) L6Pdm 6

Procedural vs Functional Procedural vs Functional

Program: a sequence Program: a sequence of instructions for a of instructions for a von Neumann m/c.von Neumann m/c.

Computation by Computation by instruction execution.instruction execution.

Iteration.Iteration. Modifiable or Modifiable or

updateable variables.updateable variables.

Program: a collection Program: a collection of function definitions of function definitions (m/c independent).(m/c independent).

Computation by term Computation by term rewriting.rewriting.

Recursion.Recursion. Assign-only-once Assign-only-once

variables.variables.

Page 7: Programming Paradigms

cs7100(Prasad) L6Pdm 7

Functional Style : IllustrationFunctional Style : Illustration

Definition : Definition : Equations Equations

sum(0) = 0sum(0) = 0sum(n) = n + sum(n-1)sum(n) = n + sum(n-1)

Computation : Computation : Substituition and ReplacementSubstituition and Replacement

sum(2)sum(2)= = 2 + sum (2-1)2 + sum (2-1)== ……= = 33

Page 8: Programming Paradigms

cs7100(Prasad) L6Pdm 8

Paradigm vs LanguageParadigm vs Language

Imperative StyleImperative Style

i := 0; sum := 0;i := 0; sum := 0;

while (i < n) dowhile (i < n) do

i := i + 1;i := i + 1;

sum := sum + isum := sum + i

end;end;– Storage efficientStorage efficient

Functional StyleFunctional Style

func sum(i:int) : int;func sum(i:int) : int;

if i = 0 if i = 0

then 0then 0

else i + sum(i-1)else i + sum(i-1)

end;end;– No Side-effectNo Side-effect

Page 9: Programming Paradigms

cs7100(Prasad) L6Pdm 9

Role of VariablesRole of Variables

Imperative (read/write)Imperative (read/write)

i 0 1 2 3 ...i 0 1 2 3 ...

sum 0 1 3 6 ...sum 0 1 3 6 ... Functional (read only)Functional (read only)

i1 sum1i1 sum1

i2 sum2i2 sum2

i3 sum3i3 sum3

......

3

2

1

6

3

1

Page 10: Programming Paradigms

cs7100(Prasad) L6Pdm 10

Bridging the GapBridging the Gap

Tail recursive programs can be auomatically Tail recursive programs can be auomatically optimized for space by translating them into optimized for space by translating them into equivalent while-loops.equivalent while-loops.

func sum(i : int, r : int) : int;func sum(i : int, r : int) : int;

if i = 0 then rif i = 0 then r

else sum(i-1, i+r)else sum(i-1, i+r)

endend– Scheme does not have loops.Scheme does not have loops.

Page 11: Programming Paradigms

cs7100(Prasad) L6Pdm 11

AnalogyAnalogy: Styles : Styles vsvs Formalisms Formalisms

IterationIteration

Tail-RecursionTail-Recursion

General RecursionGeneral Recursion

Regular ExpressionRegular Expression

Regular GrammarRegular Grammar

Context-free GrammarContext-free Grammar

Page 12: Programming Paradigms

cs7100(Prasad) L6Pdm 12

Logic Programming ParadigmLogic Programming Paradigm

Integrates Data and Control StructuresIntegrates Data and Control Structures

edge(a,b).edge(a,b).

edge(a,c).edge(a,c).

edge(c,a).edge(c,a).

path(X,X).path(X,X).

path(X,Y) :- edge(X,Y).path(X,Y) :- edge(X,Y).

path(X,Y) :- edge(X,Z), path(Z,Y).path(X,Y) :- edge(X,Z), path(Z,Y).

Page 13: Programming Paradigms

cs7100(Prasad) L6Pdm 13

Declarative Programming Declarative Programming

A logic program defines a set of relations.A logic program defines a set of relations.

This “knowledge” can be used in various This “knowledge” can be used in various ways by the interpreter to solve different ways by the interpreter to solve different queries.queries.

In contrast, the programs in other languagesIn contrast, the programs in other languages

make explicit make explicit HOWHOW the “declarative the “declarative knowledge” is used to solve the query.knowledge” is used to solve the query.

Page 14: Programming Paradigms

cs7100(Prasad) L6Pdm 14

AppendAppend in Prolog in Prolog

append([], L, L).append([], L, L).

append([ H | T ], L, [ H | R ]) :-append([ H | T ], L, [ H | R ]) :-

append(T, L, R).append(T, L, R). True statements about True statements about appendappend relation. relation.

» ““.” and “:-” are logical connectives that stand for .” and “:-” are logical connectives that stand for ““andand” and “” and “ifif” respectively.” respectively.

Uses pattern matching.Uses pattern matching.» ““[]” and “|” stand for []” and “|” stand for empty listempty list and and conscons operation. operation.

Page 15: Programming Paradigms

cs7100(Prasad) L6Pdm 15

Different Kinds of QueriesDifferent Kinds of Queries

VerificationVerification– sig:sig: list x list x list list x list x list

» append([1], [2,3], [1,2,3]).append([1], [2,3], [1,2,3]).

ConcatenationConcatenation– sig:sig: list x list -> list list x list -> list

» append([1], [2,3], R).append([1], [2,3], R).

Page 16: Programming Paradigms

cs7100(Prasad) L6Pdm 16

More QueriesMore Queries

Constraint solvingConstraint solving– sig:sig: list x list -> list list x list -> list

» append( R, [2,3], [1,2,3]).append( R, [2,3], [1,2,3]).

– sig:sig: list -> list x list list -> list x list» append(A, B, [1,2,3]).append(A, B, [1,2,3]).

GenerationGeneration– sig:sig: -> list x list x list -> list x list x list

» append(X, Y, Z).append(X, Y, Z).

Page 17: Programming Paradigms

cs7100(Prasad) L6Pdm 17

expressivenessmechanization

Logic Programming Paradigm

Knowledge Representation

Knowledge Representation

Theorem Proving

Theorem Proving

Attribute Grammars / Compilers (DCGs)Attribute Grammars / Compilers (DCGs)

Relational DatabasesRelational Databases

Programming Languages

Programming Languages

Problem Solving in AI(i)Search

(ii)Divide and Conquer

Problem Solving in AI(i)Search

(ii)Divide and Conquer

unification

declarativeness

efficiency

Trading expressiveness for efficiency :Executable specification

Page 18: Programming Paradigms

cs7100(Prasad) L6Pdm 18

Object-Oriented StyleObject-Oriented Style

Programming with Programming with Abstract Data TypesAbstract Data Types– ADTs specify/describe behaviors.ADTs specify/describe behaviors.

Basic Program Unit: Basic Program Unit: ClassClass– Implementation of an ADT.Implementation of an ADT.

» Abstraction enforced by encapsulation.Abstraction enforced by encapsulation.

Basic Run-time Unit: Basic Run-time Unit: ObjectObject– Instance of a class.Instance of a class.

» Has an associated Has an associated state.state.

Page 19: Programming Paradigms

cs7100(Prasad) L6Pdm 19

Procedural vs Object-OrientedProcedural vs Object-Oriented

Emphasis on Emphasis on procedural abstraction.procedural abstraction.

Top-down design;Top-down design;

Step-wise refinement.Step-wise refinement. Suited for Suited for

programming in the programming in the small.small.

Emphasis on data Emphasis on data abstraction.abstraction.

Bottom-up design;Bottom-up design;

Reusable libraries.Reusable libraries. Suited for Suited for

programming in the programming in the large.large.

Page 20: Programming Paradigms

cs7100(Prasad) L6Pdm 20

Integrating Heterogeneous DataIntegrating Heterogeneous Data

In C, Pascal, etc., useIn C, Pascal, etc., use

Union Type / Switch StatementUnion Type / Switch Statement

Variant Record Type / Case StatementVariant Record Type / Case Statement

In C++, Java, Eiffel, etc., useIn C++, Java, Eiffel, etc., use

Abstract Classes / Virtual FunctionsAbstract Classes / Virtual Functions

Interfaces and Classes / Dynamic BindingInterfaces and Classes / Dynamic Binding

Page 21: Programming Paradigms

cs7100(Prasad) L6Pdm 21

ComparisonComparison : Figures : Figures exampleexample

DataData– SquareSquare

» sideside

– CircleCircle» radiusradius

Operation (area)Operation (area)– Square Square

» side * sideside * side

– CircleCircle» PI * radius * radiusPI * radius * radius

ClassesClasses– SquareSquare

» sideside

» area area

(= side * side)(= side * side)

– CircleCircle» radiusradius

» areaarea

(= PI*radius*radius)(= PI*radius*radius)

Page 22: Programming Paradigms

cs7100(Prasad) L6Pdm 22

Adding a new operationAdding a new operation

DataData

...... Operation (area)Operation (area) Operation (perimeter)Operation (perimeter)

– SquareSquare» 4 * side4 * side

– CircleCircle» 2 * PI * radius2 * PI * radius

ClassesClasses– SquareSquare

» ......

» perimeterperimeter

(= 4 * side)(= 4 * side)

– CircleCircle» ......

» perimeterperimeter

(= 2 * PI * radius)(= 2 * PI * radius)

Page 23: Programming Paradigms

cs7100(Prasad) L6Pdm 23

Adding a new data representationAdding a new data representation

DataData– ......

– rectanglerectangle» lengthlength

» widthwidth

Operation (area)Operation (area)– ......

– rectanglerectangle» length * widthlength * width

ClassesClasses– ......

– rectanglerectangle» lengthlength

» widthwidth

» area area

(= length * width)(= length * width)

Page 24: Programming Paradigms

cs7100(Prasad) L6Pdm 24

Procedural vs Object-OrientedProcedural vs Object-Oriented

New operations cause New operations cause additive additive changeschanges in in procedural style, but require modifications procedural style, but require modifications to all existing “class modules” in object-to all existing “class modules” in object-oriented style.oriented style.

New data representations cause New data representations cause additive additive changes in object-oriented style, but require changes in object-oriented style, but require modifications to all “procedure modules”.modifications to all “procedure modules”.

Page 25: Programming Paradigms

cs7100(Prasad) L6Pdm 25

Object-Oriented ConceptsObject-Oriented Concepts

Data Abstraction (specifies behavior)Data Abstraction (specifies behavior) Encapsulation (controls visibility of names)Encapsulation (controls visibility of names) Polymorphism (accommodates various Polymorphism (accommodates various

implementations)implementations)

Inheritance (facilitates code reuse)Inheritance (facilitates code reuse) Modularity (relates to unit of compilation)Modularity (relates to unit of compilation)

Page 26: Programming Paradigms

cs7100(Prasad) L6Pdm 26

Example : Example : Role of interface in decouplingRole of interface in decoupling

ClientClient

» Determine the number of elements in a collection.Determine the number of elements in a collection. SuppliersSuppliers

» Collections : Vector, String, List, Set, Array, etcCollections : Vector, String, List, Set, Array, etc

Procedual StyleProcedual Style» A client is responsible for invoking appropriate A client is responsible for invoking appropriate

supplier function for determining the size.supplier function for determining the size.

OOP StyleOOP Style» Suppliers are responsible for conforming to the Suppliers are responsible for conforming to the

standard interface required for exporting the size standard interface required for exporting the size functionality to a client.functionality to a client.

Page 27: Programming Paradigms

cs7100(Prasad) L6Pdm 27

Client in SchemeClient in Scheme

(define (size C) (define (size C) (cond (cond ( (vector? C) (vector-length C) )( (vector? C) (vector-length C) ) ( (pair? C) (length C) )( (pair? C) (length C) ) ( (string? C) (string-length C) )( (string? C) (string-length C) ) ( else “( else “size not supportedsize not supported”) )”) )))))

(size (vector 1 2 (+ 1 2)))(size (vector 1 2 (+ 1 2)))(size ‘(one “two” 3))(size ‘(one “two” 3))

Page 28: Programming Paradigms

cs7100(Prasad) L6Pdm 28

Suppliers and Client in JavaSuppliers and Client in Java

interfaceinterface Collection { Collection { intint size(); } size(); }classclass myVector myVector extendsextends Vector Vector

implementsimplements Collection { Collection {}}classclass myString myString extendsextends String String

implementsimplements Collection { Collection { publicpublic intint size() { size() { returnreturn length();} length();}}}classclass myArray myArray implementsimplements Collection { Collection { intint[] array;[] array; publicpublic intint size() { size() {returnreturn

array.length;}array.length;}}}

Collection c = Collection c = newnew myVector(); c.size(); myVector(); c.size();