CSC 434 Programming Languages Fall 2001 Why Study

  • Slides: 68
Download presentation
CSC 434 Programming Languages Fall 2001

CSC 434 Programming Languages Fall 2001

Why Study P. L. ’s? u. Broader point of view u. Employability u. Pick

Why Study P. L. ’s? u. Broader point of view u. Employability u. Pick appropriate P. L. for the job u. Design a new P. L. u. Use in implementing a P. L.

Programming Paradigms u. Imperative u. Functional u. Logic u. Object oriented u. Distributed /

Programming Paradigms u. Imperative u. Functional u. Logic u. Object oriented u. Distributed / parallel

Criteria for Evaluating Programming Languages u. Expressive power u. Simplicity and orthogonality u. Implementation

Criteria for Evaluating Programming Languages u. Expressive power u. Simplicity and orthogonality u. Implementation u. Error detection and correction u. Program correctness and standards

Expressive Power u Writability control structures data structures operators modularity u Readability syntax !

Expressive Power u Writability control structures data structures operators modularity u Readability syntax ! maintenance

Simplicity and Orthogonality u. Levels of precedence (15 in C) u. Not too many

Simplicity and Orthogonality u. Levels of precedence (15 in C) u. Not too many constructions, with all combinations valid and no special cases K++ ++K K += 1 K = K + 1

Implementation Issues Cost and Efficiency u Compiling 2 stages faster execution u Interpreting 1

Implementation Issues Cost and Efficiency u Compiling 2 stages faster execution u Interpreting 1 stage slower execution

The Stages of Compiling Source program Lexical phase Tokens Syntax phase Parse tree Semantic

The Stages of Compiling Source program Lexical phase Tokens Syntax phase Parse tree Semantic phase Object program

Error Detection and Correction u Type checking u Pointer problems u Array subscripts out

Error Detection and Correction u Type checking u Pointer problems u Array subscripts out of range u Run-time exceptions …

Correctness and Standards u BASIC versus Ada for standards u Program structure u Formal

Correctness and Standards u BASIC versus Ada for standards u Program structure u Formal proofs (predicate calculus) invariants pre-conditions and post-conditions

Evolution of P. L. ’s (1 of 2) u Fortran – surprising success of

Evolution of P. L. ’s (1 of 2) u Fortran – surprising success of 1 st HLL u Algol 60 – reasons it did not succeed, but enormous influence, BNF u COBOL – data processing, influence of DOD u PL/1 – synthesis of Fortran and COBOL u Basic – original simplicity, time-sharing, lack of a standard

Evolution of P. L. ’s (2 of 2) u Pascal – for teaching CS

Evolution of P. L. ’s (2 of 2) u Pascal – for teaching CS concepts, influence of strong typing u C – for systems programming, weak typing u Ada – influence of DOD, rigorous standard u Modula-2 – simpler alternative to Ada u Others – Lisp, Prolog, C++, Java, … See Appendix 1, pp. 329 -345

Syntax and Semantics of P. L. ’s Backus Normal Form (BNF) u Syntax versus

Syntax and Semantics of P. L. ’s Backus Normal Form (BNF) u Syntax versus semantics u BNF is a meta-language, first used for Algol 60 u A grammar G defines a language L(G) u The grammar G can be used: to generate a valid sentence in L(G) to recognize if a given sentence is valid according to the rules of G

Elements of BNF Syntax u. Consists of rules, or productions u: : = means

Elements of BNF Syntax u. Consists of rules, or productions u: : = means ‘is defined to be’ u| means ‘or’ u. Identifiers within ‘< >’ are syntactic categories, or non-terminal symbols u. Other symbols are terminal symbols that represent themselves literally

Example of a BNF Grammar <exp> : : = <exp> + <term> | <exp>

Example of a BNF Grammar <exp> : : = <exp> + <term> | <exp> - <term> | <term> : : = <term> * <factor> | <term> / <factor> | <factor> : : = ( <exp> ) | <identifier>

Other Features of Syntax u Ambiguous grammars – the dangling else u EBNF uses

Other Features of Syntax u Ambiguous grammars – the dangling else u EBNF uses [ ] for optional items and { } for zero or more repetitions <integer> : : = [+|-] <unsigned integer> <identifier> : : = <letter> { <letter> | <digit> } u Syntax diagrams a graphical form of EBNF

Semantics of P. L. ’s – Harder! u Operational Semantics – uses a virtual

Semantics of P. L. ’s – Harder! u Operational Semantics – uses a virtual machine u Denotational Semantics – manipulates mathematical objects u Axiomatic Semantics – uses predicate calculus to prove properties of program statements

Miscellaneous P. L. Syntax u Special words in a P. L. keywords – meaning

Miscellaneous P. L. Syntax u Special words in a P. L. keywords – meaning varies with context reserved words – meaning is fixed u Use of blanks (Fortran example) u Comments /* … */ // … u Case sensitivity – why it might be avoided

Block Structure u Nested functions / procedures u Scope of variables (inside out) local

Block Structure u Nested functions / procedures u Scope of variables (inside out) local variables non-local variables global variables u Storage categories (lifetime) static storage automatic storage dynamic storage

Bindings u Binding name to its declaration – scope u Binding declaration to its

Bindings u Binding name to its declaration – scope u Binding declaration to its reference – lifetime u Binding reference to its value – assignment u When do bindings occur? compile time? load time? run time? u own variables in Algol 60, static in C u Finding value, given address is dereferencing

Static Scope and Dynamic Scope u In static scope a procedure is called in

Static Scope and Dynamic Scope u In static scope a procedure is called in the environment of its definition – can be determined at compile time. u In dynamic scope a procedure is called in the environment of its caller – must be determined at run time. u Hazards of dynamic scope.

Static Scope and Dynamic Scope PROGRAM Dynamic (input, output); VAR x: integer; PROCEDURE a;

Static Scope and Dynamic Scope PROGRAM Dynamic (input, output); VAR x: integer; PROCEDURE a; BEGIN … write (x); … END; PROCEDURE b; VAR x: real; BEGIN … x : = 2. 0; … a; … END; BEGIN … x : = 1; … b; … a; … END.

Binding the Type u Strong typing (static) is good – catch errors at compile

Binding the Type u Strong typing (static) is good – catch errors at compile time – Pascal, Ada u Implicit typing – e. g. , first letter of variable name in Fortran, $ suffix in Basic, … u Type inferencing – type determined at run time, can change during execution – APL

Simple Data Types u Primitive Data Types (portability ? ? ) boolean (not in

Simple Data Types u Primitive Data Types (portability ? ? ) boolean (not in C) integers reals complex (in Fortran) u Enumerated Types day = (Sun, Mon, Tues, Wed, Thurs, Fri, Sat); u Subrange Types work = Mon. . Fri;

Pointer Variables TYPE integerpt = ^integer; VAR p: integer; pipoint, another: integerpt; new (pipoint);

Pointer Variables TYPE integerpt = ^integer; VAR p: integer; pipoint, another: integerpt; new (pipoint); pipoint^ : = 17; another : = pipoint; Another is now an alias for pipoint. If we deallocate using pipoint, the memory block is gone, but another still refers to it – a dangling reference – a severe source of runtime errors.

Data Structures u Arrays u Records u Sets u Strings u Dynamic lists stacks

Data Structures u Arrays u Records u Sets u Strings u Dynamic lists stacks queues trees graphs – using pointers

Arrays u Index type and base type u Array storage allocation – the dope

Arrays u Index type and base type u Array storage allocation – the dope vector u Array sizes – static, semi-dynamic, dynamic u Cross-sections or slices u Equivalence structural equivalence name equivalence

Name/Structural Equivalence TYPE first = ARRAY [1. . 10] OF integer; second = ARRAY

Name/Structural Equivalence TYPE first = ARRAY [1. . 10] OF integer; second = ARRAY [1. . 10] OF integer; VAR a: first; b: second; c: ARRAY [1. . 10] OF integer; d, e: ARRAY [1. . 10] OF integer; f: first;

Records u Arrays use indexing – A[j, k] – homogeneous elements Records use qualification

Records u Arrays use indexing – A[j, k] – homogeneous elements Records use qualification – R. field – heterogeneous fields u Arrays with records as elements Records with arrays as fields u Variant records – conserve memory a fixed part a tag field, or discriminant a variant part but variant part may not correspond to tag!

Records – An Example TYPE spouse = RECORD name: ARRAY [1. . 10] OF

Records – An Example TYPE spouse = RECORD name: ARRAY [1. . 10] OF CHAR; age: INTEGER; END; employee = RECORD name: ARRAY [1. . 20] OF CHAR; bday: ARRAY [1. . 3] OF INTEGER; wage: real; status: char; spice = ARRAY [1. . n] OF spouse; END;

Records – Another Example TYPE shape = (circle, triangle, rectangle); colors = (red, green,

Records – Another Example TYPE shape = (circle, triangle, rectangle); colors = (red, green, blue); figure = RECORD filled: boolean; color: colors; CASE form: shape OF circle: (diameter: real); triangle: (leftside: integer; riteside: integer; angle: real); rectangle: (side 1: integer; side 2: integer); END; VAR myfigure: figure;

Sets & Strings u Set representations the characteristic vector union / intersection via OR

Sets & Strings u Set representations the characteristic vector union / intersection via OR / AND u String representations terminal characters fixed-length strings varying-length strings count-delimited strings indexed list of strings linked list strings

Evaluating Expressions u Overloading u Short u Type of operators circuit evaluation conversions mixed

Evaluating Expressions u Overloading u Short u Type of operators circuit evaluation conversions mixed mode arithmetic assignment coercion of parameters casts

Control Structures u Sequential Processing do A, then B, then C, … u Conditional

Control Structures u Sequential Processing do A, then B, then C, … u Conditional Processing (branching or selection) if A is true, then do B, else do C u Iterative Processing (looping or repetition) while A is true, do B {and test A again} u Exceptions

Issues with Iteration u Is lcv a floating point variable? u Is lcv declared

Issues with Iteration u Is lcv a floating point variable? u Is lcv declared explicitly or implicitly? u What is value of lcv when loop terminates? u When is termination test done? u Can lcv be changed inside the loop? u Can the loop be exited from the middle?

Structuring Programs u Procedures, functions, subroutines, … u Formal versus actual parameters u Named

Structuring Programs u Procedures, functions, subroutines, … u Formal versus actual parameters u Named parameters u Default parameters u Overloading of function names – signatures u Independent versus separate compilation

Parameter Passing u Principal methods call by value-result call by reference call by name

Parameter Passing u Principal methods call by value-result call by reference call by name u Complications with aliasing

Parameter Passing VAR element: integer; a: ARRAY [1. . 2] OF integer; PROCEDURE whichmode

Parameter Passing VAR element: integer; a: ARRAY [1. . 2] OF integer; PROCEDURE whichmode (x: ? MODE integer) BEGIN a[1] : = 6; element : = 2; x : = x + 3; END; BEGIN a[1] : = 1; a[2] : = 2; element : = 1; whichmode (a[element]); …

Elements of OOP u. Encapsulation – information hiding, as with ADT’s – modules, packages,

Elements of OOP u. Encapsulation – information hiding, as with ADT’s – modules, packages, classes, … u. Inheritance u. Polymorphism – as with overloading u. Dynamic binding – method call can invoke different actual methods, determined at run time

Java Abstract Classes u. An abstract method is one that has a header but

Java Abstract Classes u. An abstract method is one that has a header but no body, so cannot be implemented. u. An abstract class is one in which one or more of the methods are abstract.

Java Interfaces u Multiple inheritance would be desirable, as provided in C++, but has

Java Interfaces u Multiple inheritance would be desirable, as provided in C++, but has significant problems. u Instead Java provides interfaces. An interface contains just constants and abstract methods. Since they are all abstract, they are not labeled as such. u A class can then inherit from a parent class, and also implement several interfaces. To do so, the class must provide bodies for each of the abstract methods in the interfaces.

Java Exceptions Throwable objects include: – errors, from which there is no recovery –

Java Exceptions Throwable objects include: – errors, from which there is no recovery – unchecked exceptions, such as for arithmetical errors, which need not be (but can be!) caught and dealt with – checked exceptions, which must be caught, even if no action is provided u Code that may cause one or more exceptions is placed in a try block. u Code for dealing with exceptions is placed in catch blocks. u

Parallel Architectures u Single Instruction, Multiple Data (SIMD) u Multiple Instruction, Multiple Data (MIMD)

Parallel Architectures u Single Instruction, Multiple Data (SIMD) u Multiple Instruction, Multiple Data (MIMD) via shared memory u Multiple Instruction, Multiple Data (MIMD) via message passing u Each of these must deal with the issue of coordinating the parallel activities.

Problems of Parallelism u. Non-determinism u. Deadlock u. Starvation u. Fairness u. Termination u.

Problems of Parallelism u. Non-determinism u. Deadlock u. Starvation u. Fairness u. Termination u. Load Balancing

Solving the Preceding Problems u Semaphores are low-level, using flags set by the user

Solving the Preceding Problems u Semaphores are low-level, using flags set by the user – easy to use improperly. u Monitors are procedures that take on all of the responsibility of assigning critical resources to other processes, in response to their requests. u Rendezvous is the use of message passing to coordinate the allocation of resources and tasks to be performed. u Both monitors and rendezvous were invented by Tony Hoare!

Java Threads (1 of 3) u Java provides concurrency, which may or not be

Java Threads (1 of 3) u Java provides concurrency, which may or not be true parallelism on multiple CPU’s, via threads. u Threads can be in several states: created, running, suspended, stopped, … u Once a thread is created, one must explicitly start it; it will then perform the functionality of its run method. u Threads can be created either by extending the thread class, or by implementing the runnable interface.

Java Threads (2 of 3) u Java restricts access by competing threads to critical

Java Threads (2 of 3) u Java restricts access by competing threads to critical regions of code via the synchronized reserved word. u When a method of a Java object is synchronized, the object becomes a monitor. u When an object is a monitor in Java, then when a thread T is using one of the monitor’s synchronized methods, no other thread can use any of the monitor’s synchronized methods until T relinquishes the monitor.

Java Threads (3 of 3) u. Synchronization is still not adequate to coordinate the

Java Threads (3 of 3) u. Synchronization is still not adequate to coordinate the activities of threads. It just prevents threads from stepping on each other. u. To provide coordination, one must use wait( ) and notify( ), as with the Producer-Consumer problem.

Dijkstra’s Guarded IF if expr 1 -> stmt 1 [] expr 2 -> stmt

Dijkstra’s Guarded IF if expr 1 -> stmt 1 [] expr 2 -> stmt 2 [] … [] exprn -> stmtn fi

Dijkstra’s Guarded DO do expr 1 -> stmt 1 [] expr 2 -> stmt

Dijkstra’s Guarded DO do expr 1 -> stmt 1 [] expr 2 -> stmt 2 [] … [] exprn -> stmtn od

The Run-Time Stack u As one subprogram calls another, a run-time stack is used

The Run-Time Stack u As one subprogram calls another, a run-time stack is used to keep track of all the necessary information in a LIFO manner. u The run-time stack contains activation records, and these are linked by both static and dynamic chains. u The static chain enables a subprogram to find non-local variables according to the static scoping of subprograms. u The dynamic chain provides for appropriate return from one subprogram to its caller. Also, in the case of dynamic scoping, the system must dynamically search the records in the chain for the first occurrence of nonlocals.

Functional Languages u With imperative languages, one must know the entire state of the

Functional Languages u With imperative languages, one must know the entire state of the system, as determined by assignments to memory locations. u With functional languages, there are no assignments, just the return of function values, so there is no need to reason about the system state to be sure of the result of a computation. – no side effects – referential transparency (always same results)

Lisp and its Variants u Invented by Mc. Carthy at MIT ~ 1960 u

Lisp and its Variants u Invented by Mc. Carthy at MIT ~ 1960 u Early versions – MACLISP – Inter. Lisp – Franz Lisp – … u Now Common Lisp u Also Scheme and ML

Basics of Lists and Lisp (1 of 2) u. A List is a finite

Basics of Lists and Lisp (1 of 2) u. A List is a finite sequence (possibly empty) of elements, each of which is either an atom or a List. u The first element of a List L is (car L). u The remaining elements of a List L are (cdr L). u Example L = ((A B) C ((D))) (car L) = (A B) (cdr L) = (C ((D))) u We can represent Lists by diagrams in two ways that reflect its original implementation on a 36 -bit machine.

Basics of Lists and Lisp (2 of 2) u In our diagrams, (car L)

Basics of Lists and Lisp (2 of 2) u In our diagrams, (car L) is always either an atom or a List (cdr L) is always a List, possibly empty u Data and functions in Lisp are Lists! For a function, the first element is the function name, and the remaining elements are the arguments. u cons is used to put Lists together. Thus (cons x y) returns a List z such that (car z) is x and (cdr z) is y. Note that y must be a List!

Evaluation in Lisp u Lisp always evaluates List elements. u But evaluation is suppressed

Evaluation in Lisp u Lisp always evaluates List elements. u But evaluation is suppressed by ‘ or quote, and by the special function setq. u (setq x y) evaluates y and assigns its value to the unevaluated argument x. u So Lisp is NOT purely functional! u On the other hand eval forces evaluation. (setq x ‘(+ 2 3 4)) x is (+ 2 3 4) (eval x) is 9

Lisp: list & append u list takes any number of arguments, and builds a

Lisp: list & append u list takes any number of arguments, and builds a List containing each actual argument as an element u append takes any number of arguments (they must be Lists), and builds a List stringing together their elements u examples (list ‘(a) ‘(b (c))) is ((a) (b (c))) (append ‘(a) ‘(b (c))) is (a b (c))

Lisp: and & or u (and ( ) …) returns nil as soon as

Lisp: and & or u (and ( ) …) returns nil as soon as any argument evaluates to nil, else the value of the last argument u (or ( ) …) returns value of the first argument that evaluates to non-nil, else returns nil u Note the short-circuit evaluation

Lisp: defun (defun fn (v 1 v 2 … vn)(exp)) Lisp does not evaluate

Lisp: defun (defun fn (v 1 v 2 … vn)(exp)) Lisp does not evaluate the List elements. Rather it stores away an association of the function name fn with the parameters v 1 …. vn and the Lisp expression exp. This association is consulted whenever fn is invoked.

Lisp: cond (pred 1 exp 1) (pred 2 exp 2) … (predn expn)) Lisp

Lisp: cond (pred 1 exp 1) (pred 2 exp 2) … (predn expn)) Lisp evaluates each predj in turn. For the first one that is true, it returns with the value of the corresponding expj. If none of the predj are true, cond returns nil.

member versus ismember u (member e L) returns nil if e not in L,

member versus ismember u (member e L) returns nil if e not in L, else returns L from point of first match u (defun ismember (e L) (cond ((null L) nil) ((equal e (car L)) t) (t (ismember e (cdr L))) ))

apply, funcall, & mapcar (apply fn list) applies fn to list, returning a value

apply, funcall, & mapcar (apply fn list) applies fn to list, returning a value (apply ‘cons ‘(a (b c))) yields (a b c) funcall is like apply, except that the arguments to fn are not in a list (funcall ‘cons ‘a ‘(b c)) yields (a b c) (mapcar fn list) applies fn to each element of list, returning a new list (mapcar ‘square ‘(2 3 4 5)) yields (4 9 16 25)

PROLOG u PROgramming in LOGic u About relationships among objects u A non-procedural language

PROLOG u PROgramming in LOGic u About relationships among objects u A non-procedural language u Extremely simple syntax u Historical origins Univ. of Marseille Japanese 5 th generation initiative Univ. of Edinburgh

Prolog Facts u Relationship or predicate first u Objects in parentheses, comma between u

Prolog Facts u Relationship or predicate first u Objects in parentheses, comma between u Period at end u Example: female (alice). female (marsha). male (peter). mother (marsha, alice).

Variables and Queries u Variables are capitalized u To match query to clause in

Variables and Queries u Variables are capitalized u To match query to clause in database, must have same predicate with same arity u Instantiation of variables with goal of satisfying a query u Uninstantiation and backtracking u Anonymous variable u Closed world assumption u Reversible satisfaction

Prolog Rules and Conjunction u Conclusion in head (one predicate) u Requirements in body

Prolog Rules and Conjunction u Conclusion in head (one predicate) u Requirements in body (zero or more predicates) u : - between conclusion and requirements u Period at end happy (billy) : - day (christmas). good (Date) : - tall (Date), rich (Date).

Instantiation and Backtracking married (ben, ann). mother (ann, sue). mother (ann, tom). father (Man,

Instantiation and Backtracking married (ben, ann). mother (ann, sue). mother (ann, tom). father (Man, Child) : - married (Man, Woman), mother (Woman, Child). parent (Person, Child) : - mother (Person, Child). parent (Person, Child) : - father (Person, Child). ? - father (ben, Whom). ? - parent (Who, sue).

More Prolog u Recursion in Prolog ancestor (A, D) : - parent (A, D).

More Prolog u Recursion in Prolog ancestor (A, D) : - parent (A, D). ancestor (A, D) : - parent (A, X), ancestor (X, D). u Watch out for left recursion! u Prolog is good for: working with databases solving logic problems processing natural language (Eliza)