1 CMPE 104 Pascal (Modified slides of Tom Rethard)

Slides:



Advertisements
Similar presentations
Semantics Static semantics Dynamic semantics attribute grammars
Advertisements

ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Programming Languages and Paradigms
Statement-Level Control Structures
Programming Languages Marjan Sirjani 2 2. Language Design Issues Design to Run efficiently : early languages Easy to write correctly : new languages.
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
ALGOL 60 Design by committee of computer scientists: Naur, Backus, Bauer, McCarthy, van Wijngaarden, Landin, etc. Design by committee of computer scientists:
CS 330 Programming Languages 11 / 06 / 2007 Instructor: Michael Eckmann.
ISBN Chapter 6 Data Types: Structured types.
ISBN Chapter 8 Statement-Level Control Structures.
G. Levine Chapter 6 Chapter 6 Encapsulation –Why do we want encapsulation? Programmer friendliness- programmer need not know about these details –Easier.
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
Pascal By: Liane Tom. Outline o Background o Data types and Syntax o Procedures and Functions o Advantages o Disadvantages.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
MT311 Java Application Programming and Programming Languages Li Tak Sing ( 李德成 )
Block-Structured Procedural Languages Lecture 11: Dolores Zage.
Pascal Course Spring Introduction Designed: 1968/9 by Niklaus Wirth Published: 1970 Imperative, structural, procedural Static and strong.
Names Variables Type Checking Strong Typing Type Compatibility 1.
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
Lists Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
Neal Stublen Computer Memory (Simplified)  Remember, all programming decisions came down to a true or false evaluation  Consider.
ISBN Chapter 8 Statement-Level Control Structures.
第八章 敘述層級的控制結構 (Statement-Level Control Structures)
Programming Languages and Paradigms Imperative Programming.
Ch. 5 Ch. 51 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (more notes) Dr. Carter Tiernan.
8-1 Statement-Level Control Structures Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions.
Pascal Course Spring Introduction Designed: 1968/9 by Niklaus Wirth Published: 1970 Imperative, structural, procedural Static and strong.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
April 16, ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Chapter 4 of Programming Languages by Ravi Sethi.
Structure of Programming Languages Names, Bindings, Type Checking, and Scopes.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
Ch. 5 Ch. 51 jcmt Summer 2003Programming Languages CSE3302 Programming Languages (more notes) Summer 2003 Dr. Carter Tiernan.
Variables reference, coding, visibility. Rules for making names  permitted character set  maximum length, significant length  case sensitivity  special.
CS 330 Programming Languages 11 / 01 / 2007 Instructor: Michael Eckmann.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 Structure of Compilers Lexical Analyzer (scanner) Modified Source Program Parser Tokens Semantic Analysis Syntactic Structure Optimizer Code Generator.
Chapter 8 © 2002 by Addison Wesley Longman, Inc Introduction - Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program.
1 CSE 3302 Pascal (Using slides of Tom Rethard). 2 Algol Successful, so … Use the ideas in other languages Algol-like languages List processing String.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
CSI 3125, Data Types, page 1 Data types Outline Primitive data types Structured data types Strings Enumerated types Arrays Records Pointers Reading assignment.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
CS314 – Section 5 Recitation 9
Definition of the Programming Language CPRL
Data Types In Text: Chapter 6.
Pascal (Using slides of Tom Rethard)
Chapter 6 – Data Types CSCE 343.
Def: A control structure is a control statement and
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
8.1 Introduction - Levels of Control Flow: 1. Within expressions
CS 326 Programming Languages, Concepts and Implementation
Principles of programming languages 4: Parameter passing, Scope rules
Chapter 8: Control Structures
FORTRAN 04 February 1999; CS655.
Control Structures In Text: Chapter 8.
2017 Jan Sun Mon Tue Wed Thu Fri Sat
Types and Classes in Haskell
Jan Sun Mon Tue Wed Thu Fri Sat
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Course Overview PART I: overview material PART II: inside a compiler
REPETITION Why Repetition?
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
Presentation transcript:

1 CMPE 104 Pascal (Modified slides of Tom Rethard)

2 Pascal Designed by Niklaus Wirth Development started in 1968 First working compiler in 1970 Pascal-70 Report was on 29 pages

3 Pascal Goals Goals It is teaching language Reliability Simplicity Efficiency Wirth: “the principle to include features that were well understood, in particular by implementers, and to leave out those that were still untried and unimplemented, proved to be the most successful single guideline.” 1. The language is suitable for teaching programming in a systematic way. 2. The implementation of the language is reliable and efficient, at compile-time and run-time, on all available computers.

4 Example Program AbsMean (input, output); const Max = 900; type index = 1.. Max; var N: 0.. Max; Data: array [index] of real; sum, avg, val: real; i: index; …

5 Example (con’t) begin sum := 0; readln (N); for i := 1 to N do begin readln (val); if val < 0 then Data[i] := val else Data[i] := val end; for i := 1 to N do sum = sum + Data[i]; avg := sum/N; writeln (avg); end.

6 Enumerations Type DayOfWeek = (Sun, Mon, Tue, Wed, Thu, Fri, Sat); Month = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec); var today, tomorrow: DayOfWeek; begin … today := Tue; tomorrow := today + 1; … today = Jan; /* type error …

7 Operations := succ pred = <> < > <= >=

8 Subrange Types var DayOfMonth ; Restricts the range of values for DayOfMonth to the integer subrange of Can also use in enumerations: Type WeekDay = Mon.. Fri;

9 Sets Set of (enumeration type(char,Boolean), subrange type) Var S, T: set of 1..10; S := [1, 2, 3, 5, 7]; T := [1..6]; If T = [1, 2, 3, 5] then …

10 Set Operations = <> <= subset or equal >= But: no !

11 Arrays Any upper or lower bound Can also use enumeration types as array indices Examples var A: array [ ] of real; var HoursWorked: array [Mon.. Fri] of ;

12 Arrays Var day: Mon.. Fri; TotalHours: ; begin TotalHours := 0; for day := Mon to Fri do TotalHours := TotalHours + HoursWorked[day];

13 Arrays of Characters Any finite discrete type for index var Occur: array [char] of integer; … Occur[ch] := Occur[ch] + 1; … if Occur[‘e’] > Occur[‘t’] then …

14 More Complex Arrays var M: array [1..20] of array [ ] of real; or var m: array [1.. 20, ] of real;

15 More on Arrays Need to be static, not dynamic Must know types at compile time Dimensions are part of the array type Arrays are considered the same type if index types and base types both match

16 Type problems type vector = array [ ] of real; var U, V, vector; function sum (x: vector): real; … begin … end {sum}; Can write var W: array [1..75] of real; But cannot write: Sum(W)

17 Type Problems Types of W and of x are not the same because the ranges of the indices are different!

18 Record Types Heterogeneous data Multiple components Various types

19 Records type person = record name: string; age: ; salary: ; sex: (male, female); birthdate: date; hiredate: date; end; string = packed array [1..30] of char; date = record mon: month; day: 1..31; year: ; end; month = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);

20 Using a Record To use a record: var newhire: person; just like any other type

21 Getting to the Components var newhire: person; today: date; … newhire.age := 25; newhire.sex := female; newhire.date := today;

22 More Possibilities if newhire.name[1] = ‘A’ then … type employeeNum = ; var employees: array [employeeNum] of person; EN: employeeNum;

23 Making it Simpler with newhire begin age := 25; sex := female; date := today end;

24 Storage Groupings Homogeneous Arrays All elements are the same type Computed (dynamic) selector (subscript or index) Heterogeneous Records Elements (components) may be of different types Static selector

25 Variant Records Sometimes records vary from one record type to another. Think of this as a primitive form of subclassing

26 Variant Records type plane = record flight: ; kind: (B727, B737, B747); status (inAir, onGround, atTerminal); altitude: ; heading: ; arrival: time; destination: airport; location: airport; runway: runwayNumber; parked: airport; gate: ; departure: time; end; {plane}

27 What’s Wrong? Not all data has meaning at the same time. Can imply a plane is located at one airport and is parked at another Violates security principle.

28 Variant Records type plane = record flight: ; kind: (B727, B737, B747); case status: (inAir, onGround, atTerminal); inAir:( altitude: ; heading: ; arrival: time; destination: airport); onGround: ( location: airport; runway: runwayNumber); atTerminal: ( parked: airport; gate: ; departure: time); end; {plane}

29 Implementation flight kind status altitude heading arrival destination location runway parked gate departure

30 The Dreaded Pointer There is a problem with pointers and strong typing! Pascal solves this problem by typing pointers

31 Typed Pointers var p: ^real; x: real; c: char; begin new(p); p^ := ; c := p^; {illegal} end

32 Pointers with Records var p: ^plane; begin … p^.plane.parked[1] … … end;

33 Interpretations for equivalency Structural equivalence Structural descriptions of the types be the same Name equivalence Names must be same

34 Structural Equivalence var x: record id: integer; weight: real end; y: record id: integer; weight: real end; The above are the same because their structure is the same

35 But… Consider this type person = record id: integer; weight: real end; car = record id: integer; weight: real end; The above are the same because their structure is the same, so: car := person; according to structural equivalency is legal!

Name Equivalence var x: record id: integer; weight: real end; y: record id: integer; weight: real end; Is actually ambiguous, Different versions of Name Equivalence Rule differ on this example. If reinterpreted as follows, then they are different type T00029: record id: integer; weight: real end; T00030: record id: integer; weight: real end; var x: T00029; y: T00030;

37 Name Equivalence Issues type age = ; var n: integer; a: age; Is n:= a legal? Pure name equivalence says no Logic says yes Revised Pascal Report says that a subrange of a type is still that type

38 Comparison Name Equivalence generally safer More restrictive Name Equivalence is easier to implement Simply a string comparison Structural equivalence requires a recursive function ISO Pascal specifies name Equivalence

39 Name Structures Pascal provides six types Constant bindings Type bindings Variable bindings Procedure and function bindings Implicit enumeration bindings Label bindings

40 Constant bindings const MaxData = 100; MaxData can be used almost anywhere All declarations Executable statements (for loops, etc.) Expressions BUT, not in other const declarations! const MaxDataMinus1 = MaxData –1; is not allowed

41 Constructors Record constructors Procedure/Function The major scope defining construct

42 Procedures procedure ( ); begin end;

43 A Problem procedure P (...);... begin... Q(...)... end; procedure Q (...);... begin... P(...)... end;

44 A Problem Solved procedure Q(...) forward; procedure P (...);... begin... Q(...)... end; procedure Q (...);... begin... P(...)... end;

45 Procedure Construction procedure ( ); begin end;

46 Pascal eliminates the block Simplifies name structure Complicates efficient use of memory

47 Control structures Reflects structured programming ideas

48 For Loop for := expression { to | downto } do Bounds of the loop are computed once, at loop entry => definite iterator

49 While Loop Also a “Leading Decision Indefinite Iterator” while do Checks at top of loop Can use “while true do....” for a loop exiting from the middle (Mid-Decision Iterator)

50 Repeat Loop Also “Trailing Decision Indefinite Iterator” repeat until Checks at bottom of loop

51 Unlabeled Case Statement Modeled according to Fortran computed goto case of,,... end case;

52 case I of begin... S 1... end; begin... S 2... end; begin... S 3... end; begin... S 4... end; end case; No labels are provided.

53 Labeled Case Statement Major contribution of Pascal case of ; ;... end case; Designed by C.A. Hoare: the most important of his many contributions to language design

54 Labeled Case Statement case I of 1: begin... S 1... end; 2: 3: begin... S end; 4: begin... S 4... end; end case; Some dialects of Pascal add an otherwise case.

55 Parameter Passing Passing by reference Replaces Algol pass by name Intended to allow side effects (ie, I-O parameter usage) Passes only the address Passing by value Intended for input only parameters Side effects not allowed Done by copy-in

56 Pass as Constant Original specification contained this instead of pass by value Similar to C const parameter passing Allowed compiler to pass either address or value Called procedure could not modify it Elimination encourages call by reference

57 Procedure type vector=array[1..100] of real; var A:vector … procedure P(x:vextor); \*pass by constant begin writeln(x[1]); A[1]:=0; writeln(x[1]) end; begin P(A) end;

58 Pass as Constant Two orthogonal issues involved Should copy its value or use its address? Should be I or I-O parameter Approach violates the Orthogonality Principle

Procedure Procedure difsq (function f:real; x:real):real begin difsq:= f(x*x) – f(-x*x) end difsq(sin,theta)=sin(theta^2 ) – sin(-theta^2)

Procedure arguments The arguments of a formal procedure parameter shall be specified Procedure difsq (function f(y:real):real; x:real):real