Expressions Imperative prg : Statements have just vs side-effects, - - PowerPoint PPT Presentation

expressions
SMART_READER_LITE
LIVE PREVIEW

Expressions Imperative prg : Statements have just vs side-effects, - - PowerPoint PPT Presentation

Every expression results in a value (+side-effects?): 1+2, str.length(), f(x)+1 Expressions Imperative prg : Statements have just vs side-effects, no value: (for, if, break) statements Assignment is statement/expression depending


slide-1
SLIDE 1

171

Expressions vs statements

  • Every expression results in a value

(+side-effects?): 1+2, str.length(), f(x)+1

  • Imperative prg: Statements have just

side-effects, no value: (for, if, break)

  • Assignment is statement/expression

depending on language (a=b=c)

  • Often expression can act as a statement,

result is discarded (1+2;)

  • Functional prg: No side-effects →no

statements, just expressions (Haskell: let x = if x>0 then x else -x)

slide-2
SLIDE 2

172

Expression evaluation

  • Common subexpressions can usually

be optimized, as can constant expressions

  • Intermediate results use memory too!
  • Precedence does not determine

execution order!

  • Side-effects can complicate

evaluation (common mistake in C++)

slide-3
SLIDE 3

173

How many control structures are needed at minimum?

  • 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

slide-4
SLIDE 4

174

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/C++:

slide-5
SLIDE 5

175

Implementing conditionals

  • 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

  • f values
  • Hash-table or other dictionary
slide-6
SLIDE 6

176

Implementing if

r1 := A r2 := B r1 := r1 > r2 r2 := C r3 := D r2 := r2 > r3 r1 := r1 & r2 r2 := E r3 := F r2 := r2 <> r3 r1 := r1 | r2 if r1 = 0 goto L2 L1: then_clause goto L3 L2: else_clause L3:

if ( ( A > B ) and ( C > D ) ) or ( E <> F ) then then_clause else else_clause

Pascal: Resulting pseudo- assembly:

slide-7
SLIDE 7

177

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 address

case E of 1: S1; 2: S2; 3: S3; 4: S4; end

1 2 3 4

... S1 S2 S3 S4 ...

slide-8
SLIDE 8

178

Peculiarities

  • f 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' ].

slide-9
SLIDE 9

179

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;

  • - statements

end loop; generalisation (Ada):

slide-10
SLIDE 10

180

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

  • nly once?

Iterating an array

slide-11
SLIDE 11

181

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:

slide-12
SLIDE 12

182

Peculiarities

  • f 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. ]

slide-13
SLIDE 13

183

Loop control

OUTER_LOOP: for row in 1..max_rows loop INNER_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/C++:

slide-14
SLIDE 14

184

Loops and data structures

type Days is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); for Index in Days loop ... end loop;

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:

slide-15
SLIDE 15

185

Generators/ Coroutines

  • Functions are "single-use": parameters

in, return value out

  • Generators are "multi-use": they can be

suspended and produce multiple values (when needed)

  • In Python, generator is an iterator,

which is used to access (and calculate) the values. Generator functions return generators (iterators)

  • In C++20, coroutines are a similar

concept, with slightly different syntax

slide-16
SLIDE 16

186

Generators, example def factorials(n): f = 1; i = 1; while i <= n: yield f i=i+1; f=i*f fact = factorials(10) # print(next(i)) factsq = (x*x for x in fact) for i,f in enumerate(factsq) print(i, ":", f)

slide-17
SLIDE 17

187

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)

slide-18
SLIDE 18

188

Pipelines/ Task graphs

  • Describe computation as a sequence (or

tree) of linked steps

  • Becoming more common nowadays
  • Allows both laziness, concurrency, and

parallelism (=asynchrony)

  • Ranges + views in C++20 (expanded to

coroutines/parallelism in C++23):

auto mydata = iota(1) | filter_view(is_prime) | transform_view([](auto x){return x*x;}) | take_view(10) | reverse_view; // Nothing has been executed yet! for (auto& i : mydata) { std::cout << i << std::endl; }