b6c6f3de10dba75873de9854b6b2dc84.ppt
- Количество слайдов: 48
Programming Languages Lecture 2 1
Control Structures n Any mechanism that departs from straight-line execution: n Selection: if-statements n Multiway-selection: case statements n Unbounded iteration: while-loops n Definite iteration: for-loops n Iterations over collections n transfer of control: gotos (considered harmful!) n unbounded transfer of control: exceptions, backtracking n Characteristic of Imperative languages All you need for a universal machine: increment, decrement, branch on zero. All the rest is programmer convenience! n Not efficient on modern pipelined processors n 2
Selection n if Condition then Statement else Statement if (Condition) Statement else Statement n Selection Expression: n n --- Pascal, Ada C, C++ Java Condition ? Expression : Expression -- C Characteristic of functional languages To avoid ambiguities, use end marker: end if, fi, or bracketing { } To deal with several alternatives, use keyword or bracketing: --Ada if Condition then Statements else Statements end if; /* C */ if (Condition) { Statements} else { Statements} 3
Statement Grouping n n Pascal introduces begin-end pair to mark sequence C/C++/Java abbreviate keywords to { } Ada dispenses with brackets for sequences, because keywords for the enclosing control structure are sufficient: for J in 1. . N loop … end loop; n n More writing => more readable The use of grouping in C++/Java is just syntactic tradition Another possibility (ABC, Python): make indentation significant Nesting groups of statements if Condition then Statements end if; else Statements end if; if (Condition) { Statements } else { Statements } 4
Short-Circuit Evaluation n If x is more than five times greater than y, compute z: n if x / y > 5 then z : = … -- but what if y is 0? if y /= 0 and x/ y > 5 then z : = … -- but operators evaluate their arguments n Solutions: n n n n a lazy evaluation rule for logical operators (LISP, C, etc) a control structure with a different syntax C 1 && C 2 if C 1 and then C 2 then C 1 || C 2 if C 1 or else C 2 then does not evaluate C 2 if C 1 is false ditto does not evaluate C 2 if C 1 is true ditto 5
Multiway selection n n Generalization of condition if from boolean to any discrete type Can be simulated with a sequence of if-statements, but logic can become obscured. case (X) is -- any integer value (discrete but large) when integer’first. . 0 => Put_Line (“negative”); when 1 => Put_Line (“unit”); when 3 | 5 | 7 | 11 => Put_Line (“small prime”); when 2 | 4 | 6 | 8 | 10 => Put_Line (“small even”); when 21 => Put_Line (“house wins”); when 12. . 20 | 22. . 99 => Put_Line (“manageable”); when others => Put_Line (“Irrelevant”); end case; n All choices must be computable at compile-time 6
The well-structured case statement C Y Ada Y Each choice is independent of the others (no flowthrough) N Y All possible choices are covered exactly once N Y There is mechanism to specify a default outcome for choices not given explicitly. Y Y Enforced in Type of expression must be discrete: an enumerable set of values (floating-point numbers not acceptable) 7
Loops n Definite Loops n for J in Integer range 1. . 10 loop statements end loop; n Indefinite Loops n while condition loop n end loop; loop statements end loop; n All loops can be expressed as while-loops (e. g. , in C) for (i = 0; i <10; i++) … equivalent to: i=0; while (i<10) { … i++; } n n Condition is evaluated at each iteration If condition is initially false, loop is never executed while Condition loop. . end loop; n equivalent to if Condition then while Condition loop … end loop; end if; 8
What if we want to execute at least once? n n Pascal introduces until-loop. C/C++ use different syntax with while: while (Condition) { … } do { … } while (Condition) n Can always simulate with a boolean variable: done : = False; while (not done) loop … if Condition then done : = True; end loop; 9
Unstructured flow (Duff’s device) void send (int* to, int* from, int count) { int n = (count + 7 ) / 8; switch (count % 8) { case 0 : do { *to++ = *from++; case 7 : *to++ = *from++; case 6 : *to++ = *from++; case 5 : *to++ = *from++; case 4 : *to++ = *from++; case 3 : *to++ = *from++; case 2 : *to++ = *from++; case 1 : *to++ = *from++; } while (--n >0); } What does this do? Why bother? 10
Breaking out n n More common is the need for an indefinite loop that terminates in the middle of an iteration. C/C++/Java: break n n Break out of while, do, for, switch statements Ada : exit statement loop -- infinite loop compute_first_part; exit when got_it; compute_some_more; end loop; 11
Breaking out of Nested Loops n n n Within nested loops, useful to specify exit from several of them Ada solution: give names to loops Otherwise: use a counter (Modula) or use a goto. Outer: while C 1 loop. . . Inner: while C 2 loop. . . Innermost: while C 3 loop. . . exit Outer when Major_Failure; exit Inner when Small_Annoyance; . . . end loop Innermost; end loop Inner; end loop Outer; 12
Definite loops n n Counting loops are iterators over discrete domains: for J in 1. . 10 loop … for (int I = 0; I < N; I++ ). . Design issues: n n n Evaluation of bounds (only once, ever since Algol 60) Scope of loop variable Empty loops Increments other than one Backwards iteration non-numeric domains 13
The loop variable n n n n n Best if local to loop and treated as constant Avoids issue of value at termination, and value on abrupt exit counter : integer : = 17; -- outer declaration. . . for counter in 1. . 10 loop do_something; -- 1 <= counter <= 10 end loop; … -- counter is still 17 14
Different increments n The universal Algol 60 form: for J from Exp 1 to Exp 2 by Exp 3 do… n n n Too rich for most cases. Exp 3 is most often +1, -1. What is meaning if Exp 1 > Exp 2 and Exp 3 < 0 ? In C/ C++ for (int J = Exp 1; J <= Exp 2; J = J + Exp 3) … n In Ada: for J in 1. . N loop for J in reverse 1. . N loop n -- increment is +1 -- increment is -1 Everything else can be programmed with while-loop 15
Non-numeric domains n Ada form generalizes to discrete types: for M in months loop … n General pattern for other data-types: define iterator class with primitive operations: has. Next(), next() Iterator it = Collection. Iterator(); while (it. has. Next) { element = it. next(); … } n APL avoids the need for iterators by automatically extending scalar operations over composite data types a 123 b 321 1 + a is 2 3 4 a + b is 4 4 4 16
Recursion n Example: int fib(int n) { } n n return (n <= 1) ? 1 : fib(n-1) + fib(n-2); Tail Recursion – when function returns immediately after recursive call – can be automatically transformed into a loop List processing with recursion int max(List
Assignment n n Assignment always produces a side effect variable : = expression; lvalue : = rvalue n lvalue (left hand value) must be an address or reference. e. g. , x, x[i] but not (x + 1) n rvalue (right hand value) is a value n n n Types must match In Ada, assignment is a statement In C, C++, and Java it is an expression Initialization vs. Assignment Combination Assignment n n X = X + 1 -- a mathematical absurdity X += 1 -- simpler and clearer 18
Precedence & Associativity n Most languages enforce standard mathematical rules APL doesn’t. Evaluation is always right to left n Same for Smalltalk n n C++ has 18 levels of precedence Even if you know them all, the next maintenance programmer might not n Use parentheses n 19
Continuations n n n A Continuation represents a point in the computation, including all of the state information at that point All control structures (function calls, loops, if, exceptions, goto, etc. ) can be described using continuations Scheme supports continuations as 1 st class objects 20
An Introduction to Ada 21
What’s ADA all about n n Designed by committee for Do. D Key goals: n n Readability Strong typing n n Programming in the Large – Packages n n n n Detection of errors at compile time Encapsulation Separate compilation Data Abstraction Run-time Error Handling – Exceptions Reliable multi-Tasking Generic Units – parameterized types Emphasis on Programming as a Human Activity 22
Hello, World A simple Ada Program, hello. ada with text_IO; procedure hello is use text_IO; begin put(“Hello, World”); end hello; n 23
Basic Structure of an ADA Program n Program Units n n Subprograms n n n Packages, subprograms and tasks Procedures (do not return a value) Functions (return a value) Packages n n Collection of related data types functions and procedures Provides services to clients May use services of other packages Defined in two parts n n Package Specification (. ads, . spc) Package Body (. adb, . bdy) 24
Package Specification n n Contain Declarations package X is declarations types subprogram specs (but not subprogram bodies) end X; Specification provides public interface for users of the package, but no implementation details Specification is like a contract between the package and its clients 25
Subprogram Specification procedure Print_In_Hex (X : Integer); function Max (A, B : Integer) return Integer; n Similar to signatures in C and C++ header files. n n Headers can be generated automatically from the source code Java does this automatically with import statement A subprogram spec has everything you need to know to use the subprogram A client sees only the specification n n Implementation details are hidden Implementation can be changed without affecting clients 26
Procedure Body n procedure H (M : Integer) is declarations begin statements n n return; end H; Typical use is procedure Main is … which defines the main program File name must match main procedure name 27
Function Body n function Max (A : Integer; B : Integer) return Integer is Result : Integer; begin if A > B then Result : = A; else Result : = B; end if; return Result; end Max; 28
Package Bodies n n Contain Definitions package body X is declarations subprograms local to body variables/constants local to body subprogram bodies for subprogram specs appearing in the package spec begin initialization statements end X; 29
How to be a Client of a package n n To access a package, use With and Use statements: with Calendar, Text_IO; use Text_IO; procedure Main is Today : Calendar. Time; put(“Today is” ); … end Main; Use eliminates the need to specify the package name, as in Calendar. Time, when using a package member 30
Package Clients n Package Bodies with Calendar; package body Julian_Calendar_Stuff is … end Julian_Calendar_Stuff; n n Package implemented using another package Package Specifications n n with Calendar; use Calendar; package To_Do_List is … procedure Enter (T : Time; M : String); -- Enter new item in todo list. Time is -- deadline. M is description. end To_Do_List; Package To_Do_List extends Calendar interface 31
Using Ada n Write your program using any text editor n n Save it in a file named myprog. adb, where myprog is the name of the main procedure in the program. Compile your program: gnat make myprog. adb n On windows this produces a file myprog. exe, which you can execute n On Unix you will have to make the file executable using chmod a+x myprog n Ada resources on the Web: n n n http: //www. adapower. com http: //www. adahome. com ftp: //cs. nyu. edu/pub/gnat 32
Writing an ADA Program n n n Write the package specifications Verify that specification is usable by intended clients Write the body Write the clients Last two activities are completely independent (and should not talk to one another except “via” the spec) 33
Ada Operators Logical Operators: Relational Operators: Additive Operators: and or xor = /= < <= > >= + – & & is concatenation on vectors and strings Unary Operators: + – not Multiplicative Operators: * / mod rem Exponentiation Operator: ** 34
Integer Types n n Type Integer is built in – But you don’t want to use it! In ADA types are defined according to use type Day_In_Year is range 1. . 366; type Age is range 0. . 130; type Temperature is range -20. . +180; n Now we can define variables of the type Today_Day : Day_In_Year; Employee_Age : Age; Machine_Room_Temp : Temperature; n Type Attributes n n n Integer’last, Year’last Integer’first, Age’first for A in Age’first … Age’last loop 35
Strong Typing n n No dependence on implementation -- Unlike type int in C Range of types matches problem n Get an error or warning at compile time n n Or an exception at runtime n n Age : = 200; Age : = Age + 1000; Cannot mix integer types: Current_Temp : Temperature; OK Current_Pressure : Pressure; OK Current_Temp : = Current_Pressure + 1; Error Current_Temp : = Current_Temp + Current_Pressure; Error n Type Errors detected at Compile Time 36
Integer Subtypes n n A subtype creates a limited range But is still the same type n subtype OK_Operating_Range is Temperature range 70. . 80; Room_Temp : Temperature; Machine_Room_Temp : OK_Operating_Range … Machine_Room_Temp : = Room_Temp; n Raises exception if Room_Temp out of range 37
Enumeration Types n An enumeration type is a sequence of ordered enumeration literals: n n n Type State is (Off, Powering_Up, On); Type Color is (Red, Orange, Yellow, Blue, Green); Not integers (as in C++) S 1, S 2 : State; S 1 : = S 1 + 1; – Error, but State’Pred (On) – OK, Powering_Up State’Succ (On) – OK, but raises constraint_error n Predefined enumeration type n n type Boolean is (False, True); Other Attributes include: T’First, T’Last, T’Val(n) where n is a value in T 38
Character Types n Built in types Character (8 -bit Latin-1) n Wide_Character (16 -bit Unicode/ISO 10646) n n Good enough for most purposes, but you can define your own types: n type My_Character is (‘A’, ‘B’, ‘C’, …. ); 39
String Types n n A string type is an array whose elements are a character type. Two standard built in string types type String is array (Natural range <>) of Character; type Wide_String is array (Natural range <>) of Wide_Character; S : String (1. . 5) : = “Hello”; n Note: Natural is a predefined subtype of Integer with bounds 0. . Integer’Last; n 40
Array Types n Arrays can have 1 or more subscripts n type Vector is array (Integer range 1. . 10) of Integer; type Matrix is array (Integer range 0. . 10, Character range ‘A’. . ‘Z’) of Vector; VV : Vector; MM : Matrix; … MM (5, ‘C’) : = VV; 41
Array Attributes n A’First(N), A’Last(N), A’Length(N), A’Range(N) N is the attribute for the Nth index n N must be static n Without a parameter, attributes refer to the first index - A’First, etc. n n We can use the array range in loops for x in A’Range loop result : = result + A[x]; end loop; 42
Unconstrained Arrays n Unconstrained array type has no bounds n type UA is array (Int range <>) of Int; -- cannot use UA to declare a variable -- instead must build a subtype UA 5 is UA (1. . 5); UAV 5 : UA 5 : = (6, 5, 4, 3, 2); -- can also set bounds for a variable UAV 2 : UA (1. . 2); 43
Access Types n Access types function like pointers n n n Allocate an object using new n n But are not necessarily implemented that way type r is access integer; type AI is access all integer; Ptr : AI; … Ptr : = new Integer; -- uninitialized Ptr : = new Integer’(12); -- initialized To obtain value dereference: n V : Integer; … V : = Ptr. all; 44
Declaring and Handling Exceptions n Declaring an exception n n Raising an exception n n Error, Disaster : exception; raise Disaster; -- strips stack frames till a handler is found Handling an exception when Disaster => statements 45
Catching Exceptions n You can catch an exception at run time n begin … Machine_Room_Temp : = Room_Temp … exception when Constraint_Error => recovery stuff when Meltdown_Error => recovery stuff … end; 46
Block Statement n Block statement can be used anywhere n declare declarations -- declare section optional begin statements exception handlers -- exception section optional end; 47
Access Types n Access types function like pointers n n n Allocate an object using new n n But are not necessarily implemented that way type r is access integer; type AI is access all integer; Ptr : AI; … Ptr : = new Integer; -- uninitialized Ptr : = new Integer’(12); -- initialized To obtain value dereference: n V : Integer; … V : = Ptr. all; 48