how many control structures? - tunipopl/lecture-slides-pdf/09-control-structures.pdf · how many...
TRANSCRIPT
1Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
How many control structures?
• 1: – Conditional jump [goto-statement]
• 2: – Choice of two control-flows [if-statement]
– Logically controlled iteration [while-statement]
• Many languages have several– To improve readability and writability
– If the language is large, only some subset is often used
2Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Choice• 1-way choice (Fortran IV)
• 2-way choice (Algol60)
• multi-way (e.g. Ada)
IF ( cond ) stmt IF ( FLAG .NE. 1 ) GO TO 20I = 1J = 2
20 CONTINUE
if cond then stmtelse stmt
if ( x < 10 ) then class = ”small”;elsif ( x < 100 ) then class = ”medium”;elsif ( x < 1000 ) then class = ”large”;else class = ”huge”;end if;
3Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
case-structure
• Conditional statements based on equality– case labels (possible values)
• Design issues:– Type of the expression?
– Values of the case labels?• constants?
• Enumerated types?
• Mutually exclusive?
– Other options executed?• default, else, others -branching
case E of L1: S1; L2: S2; ... Ln: Sn;end
switch ( E ) { case L1: S1; case L2: S2; break; ... case Ln: Sn;}
Pascal:
C code:
Variablerecordoptions
4Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Implementing choice• If-statement compiling:
– Condition truth value used in conditional jump
• case-statement:– Small number of case-tags
• Compile as if-then-elsif
– Reasonable number of tags that cover the set of values• Jump address table• Empty values use the default address
– Large number of tags, and even larger set of values• Hash-table or other dictionary
5Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Implementing choices
r1 := Ar2 := Br1 := r1 > r2r2 := Cr3 := Dr2 := r2 > r3r1 := r1 & r2r2 := Er3 := Fr2 := r2 <> r3r1 := r1 | r2if r1 = 0 goto L2
L1: then_clausegoto L3
L2: else_clauseL3:
if ( ( A > B ) and ( C > D ) ) or ( E <> F ) then then_clauseelse else_clause
Pascal-koodia:
6Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Jump address table
• Each case-tag corresponds to an index
• Index points to an address for jumping when condition evaluates as the case-tag
• Code is found in the addresscase E of 1: S1; 2: S2; 3: S3; 4: S4;end
1234
...S1S2S3S4...
7Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Peculiarities of choice
• ML and Haskell: piecewise functions– fun fact(0) = 1
| fact(n : int) : int = n * fact(n-1);– fact 0 = 1
fact n = n * fact(n-1)
• Smalltalk boolean objects– Boolean inherited classes True and False
– Their methods ifTrue and ifFalse, conditional code as parameter, either executed or not
– i < 2 ifTrue: [ Transcript show: 'It is small' ].
8Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Repetition statements• Definite/bounded iteration [counter]
– The number of repetitions is known before starting
• Indefinite/unbounded iteration [logical condition]– Number of iterations is determined during the iteration
– Test of ending at the end or the beginning
loop -- statements exit when cond; -- statementsend loop;
generalisation (Ada):
9Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Definite/bounded iteration
• Contains loop index (loop counter)for index from expr1 to expr2 do stmt end
• Semantics vary between languages– Is the index value defined after execution?
– Can the index value be changed within the body?
– Are upper and lower values evaluated only once?
Iteratingan array
10Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
<for_stmt> ::= for var := <list_elem> {, <list_elem>} do <stmt><list_elem> ::= <expr> | <expr> step <expr> until <expr> | <expr> while <bool_expr>
for count := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 do list [ count ] := 0
for count := 1 step 1 until 10 do list [ count ] := 0
for count := 1, count + 1 while ( count <= 10 ) do list [ count ] := 0
for index := 1, 4, 13, 41 step 2 until 47, 3 * index while index < 1000, 34, 2, -24 do sum := sum + index
1, 4, 13, 41, 43, 45, 47, 147, 441, 34, 2, -24
Algol60:for-stmt:
for-stmtuses:
complexuse:
Indexvalues:
11Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Alternative ways of definite iteration
for variable := init_value ( to | downto ) final_value do stmt
Pascal:
for variable in [ reverse ] discrete_range loop ...end loop;
i: Float := 3.14;for i in 1..10 loop sum := sum + i;end loop;
Ada:
The scope of the index (Ada):
12Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
C for-statement
for ( index = 0; index <= 10; index++ ) sum += list [ index ];
• No actual loop index
• Three expressions– Any expression can be omitted
– Each expression may be compound
for ( count1 = 0, count2 = 1.0; count1 <= 10 && count2 <= 100.0; sum = ++count + count2, count2 *= 2.5 );
13Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
C++ and Java for-statements
• C++– ”loop indes” definition
– No effect on visibility
• Java– Truth-valued conditions
– ”loop index” is visible only inside the loop
for ( int i = 0; i < MAX; i++ )
int i;for ( i = 0; i < MAX; i++ )
14Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Value of the index after the loop
• Safe semantics:– Not visible
• If visible:– undefine
• Pascal
– Last given value(first value ”over” the limit)• esim. Fortran, Algol60
var c: ’a’..’z’;...for c := ’a’ to ’z’ do begin ...end;
Pascal:
15Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Indefinite/unbounded iteration
• End condition evaluation– beginning
• 0 – n iterations
– end• 1 – n iterations
• Ending logic:– while: continue if true
– until: end if true
s := 0;Read ( nm );while nm >= 0 do begin s := s + nm; Read ( nm );end;
s := 0;Read ( nm );repeat s := s + nm; Read ( nm );until luku < 0;
Pascal-koodia:
16Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Peculiarities of iteration• Combination of definite and indefinite
iteration (C for)
for ( E1; E2; E3 ) S; E1; while ( E2 ) { S; E3 };
• One general structure (Algol68)– Only mandatory parts: do and od
for index from expr1 by expr2 to expr3while expr4 do statement od
17Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Peculiarities of iteration
• Smalltalk iteration is an intermediate method, code block as parameter, with the value of the index as its parameter– Interval from: 1 to: 10 do: [ i | Transcript show: i ]
• Undefined iteration is a method of a code block
– [ Transcript show i. i := i-1. i > 0 ] whileTrue.
– [ i > 0 ] whileTrue: [ Transcript show i. i := i-1. ]
18Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Loop controlOUTER_LOOP: for row in 1..max_rows loopINNER_LOOP: for col in 1..max_cols loop sum := sum + mat ( row, col ); exit OUTER_LOOP when sum > 1000; end loop INNER_LOOP; end loop OUTER_LOOP;
while ( sum < 1000 ) { getnext ( value ); if ( value < 0 ) continue; sum += value;}
while ( sum < 1000 ) { getnext ( value ); if ( value < 0 ) break; sum += value;}
Ada:
C jaC++:
19Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Loops and data structurestype Days is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun );for Index in Days loop ... end loop;
int[] tbl = {1, 2, 3}; // C++: int tbl[] = {1, 2, 3};for (int i : tbl) { ... }
String [ ] strList = { ”Bob”, ”Carol”, ”Ted” };foreach ( String name in strList ) Console.WriteLine ( ”Name: ”, name );
Ada:
C#:
Lambdas and library functions used as loops
Haskell: let tbl = [1, 2, 3] in map (\x -> x*x + 1) tbl
int[] tbl = {1, 2, 3}; // C++: int tbl[] = {1, 2, 3};for (int i : tbl) { ... }
C++Java:
20Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Generators (Python)● Functions are "single-use": parameters in, return
value out● Generators are "multi-use": they can produce
multiple values (when needed)● Generator is an iterator, which is used to access (and
calculate) the values● Generator functions return generators (iterators)● (Or: normal data structures can be viewed as
generator functions with pre-calculated values, accessed through iterators)
21Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Generators, example
def firstn(n): num = 0 while num < n: yield num # "return", ready to continue num += 1
i = firstn(10)print(next(i)) ; print(next(i))j = (x*x for x in i)print(next(j))
22Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen
TUT Software Systems
Benefits of generators
• Avoid creating big data structures, create values when necessary
• Allow lazy evaluation (almost)
• Allow pipeline programming: actions (generators) are chained together, feeding values to next action (generator)