structure of programming languages lecture 6eliza.newhaven.edu/lang/attach/l6-control.pdfone-in /...

39
Structure of Programming Languages – Lecture 6 CSCI 6636 – 4536 March 10, 2020 CSCI 6636 – 4536 Lecture 6. . . 1/39 March 10, 2020 1 / 39

Upload: others

Post on 27-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structure of Programming Languages – Lecture 6

CSCI 6636 – 4536

March 10, 2020

CSCI 6636 – 4536 Lecture 6. . . 1/39 March 10, 2020 1 / 39

Page 2: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Outline

1 Expressions and Evaluation

2 Goto Statements

3 Structured ControlWhat Kinds of Control are Needed?Structured ControlConditionalsRepetitionExceptions

4 Control ExpressionsConditional Expressions

5 Homework

CSCI 6636 – 4536 Lecture 6. . . 2/39 March 10, 2020 2 / 39

Page 3: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Expressions and Evaluation

Arithmetic Expression Syntax

All programming languages support arithmetic expressions.

The four primary arithmetic operations: +,−, ∗, and / are alwayssupported.

Javascript uses ∗∗, for exponentiation.

APL has symbols for dozens of things.

Parentheses are used to influence the order of evaluation.

CSCI 6636 – 4536 Lecture 6. . . 3/39 March 10, 2020 3 / 39

Page 4: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Expressions and Evaluation

Arithmetic Expression Semantics

The syntax for expressions is not enough to define their meaning. Wemust also know the evaluation rules:

In most languages, the semantics of arithmetic expressions are definedby the rules for precedence and associativity. However, these rulesdiffer from language to language.

Some languages (Lisp, Scheme) are written in fully-parenthesizedprefix form.

Forth is written in non-parenthesized postfix form.

APL is (was) evaluated right to left, modified by parenthesizedsubexpressions. It very very difficult to comprehend the meaning of acomplex APL expression.

CSCI 6636 – 4536 Lecture 6. . . 4/39 March 10, 2020 4 / 39

Page 5: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Expressions and Evaluation

Order of Evaluation: Compile Time vs. Run Time

Precedence and associativity govern the order in which operands areparsed and added to the computation tree at compile time. They do NOTalways govern evaluation order at run time.

The order in which the run-time system evaluates the two operands of anoperator, or the arguments in a function call, is defined in some languages,undefined in others.

CSCI 6636 – 4536 Lecture 6. . . 5/39 March 10, 2020 5 / 39

Page 6: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Expressions and Evaluation

Semantics: Order of Evaluation.

In Scheme, the language semantics specify that the evaluation orderis not constrained. However, it must not matter what order is used,and the result of the operation (given the same arguments) mustalways be the same.

In C/C++, the operands/arguments can be evaluated in any orderthat is convenient for the compiler. This leaves freedom for anoptimizer to work. The result of relying on any particular evaluationorder is undefined.

In Java, the order is left-to-right.

In C#, the order is left-to-right.

CSCI 6636 – 4536 Lecture 6. . . 6/39 March 10, 2020 6 / 39

Page 7: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Expressions and Evaluation

Lazy vs. Strict Evaluation

Strict Evaluation:

Evaluate the expressions and statements in the order they are given inthe program.

Evaluate the argument-expressions before you call a function, andbind the results to the parameter name within the function.

Lazy Evaluation:

Do not evaluate an expression unless it is needed to produce theoutput.

Do not evaluate a parameter until you need it.

CSCI 6636 – 4536 Lecture 6. . . 7/39 March 10, 2020 7 / 39

Page 8: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Expressions and Evaluation

In Praise of Laziness

A result from Lambda Calculus:Outside-in evaluation is strictly more powerful than inside-out:

if ( x != 0) answer = z/x; else answer = z;

O-I: Evaluate if (x != 0) first, then choose one clause.

I-O: Evaluate z/x first and bomb with a divide-by-zero error.

Every programming language evaluates conditionals outside in. Mostlanguages evaluate everything else inside-out.

Modern functional languages use outside-in evaluation consistently; it iscalled lazy evaluation. Nothing is evaluated until and unless the result isneeded.

CSCI 6636 – 4536 Lecture 6. . . 8/39 March 10, 2020 8 / 39

Page 9: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Goto Statements

Jumps and Gotos

A goto statement transfers control to some other labelled statement in theprogram. A jump transfers control forward or backward a defined distancein the executable code.

Of course, assembly languages rely on goto for conditionals and loops.

The Forth assembler uses jumps to implement conditionals and loops.

In Basic, all lines were given numbers reflection their proper order.The target of the goto could be any specific line number.

In Fortran, labels were arbitrary identifiers, declared at the top of aprogram unit.

In C#, statement labels are alphabetic, and written at the beginningof a line. You can also goto a case statement within a switch.

A C/C++ goto is like C#, but the target cannot be a case label.

CSCI 6636 – 4536 Lecture 6. . . 9/39 March 10, 2020 9 / 39

Page 10: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Goto Statements

Go to considered harmful. . .

In 1966, a paper by Boehm and Jacopini, proved that a languagethat provides sequencing, selection, and iteration is sufficient towrite a program to compute any computable function.

In 1968 Edgar Dijkstra published “Go to considered harmful”. It describedthe relatively poorer quality of programs written by programmers whorelied on goto’s. Dijkstra advocated using if-then-else and while or repeatcontrol structures because they mirror the structure of the process betterthan multiple go-to’s.

Donald Knuth responded with an article “Go to considered harmfulconsidered harmful”, which was a defense of the need for goto’s to achievelarger-scale error handling and responsive execution.

Dijkstra and Knuth are two of the great men in Computing, and thisdebate is still famous.

CSCI 6636 – 4536 Lecture 6. . . 10/39 March 10, 2020 10 / 39

Page 11: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Goto Statements

Structured Programming

For the next ten years, textbooks pushed the idea of programming with“structured style”. Using any other control statements was considered“poor technique”.

Fortran textbooks were published that contained clumsy, inefficientimplementations of while loops and if-then-else instead of the nativecontrol statements.

One-in / one-out control structures became sacred cows: essential toavoid “spaghetti code”. Boolean status flags were used to controlexecution instead of goto’s.

Then C was introduced. It had a one-in/two-out control structure: a loopcontaining a break. By using the break effectively, the need for booleanspaghetti evaporated. Then C++ came, with exceptions. At that point,there was no longer a need for goto.

CSCI 6636 – 4536 Lecture 6. . . 11/39 March 10, 2020 11 / 39

Page 12: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Goto Statements

From the Delphi website, circa 1995:

Delphi is a dialect of Pascal, with some OO constructs added.

The Goto keyword forces a jump to a given label.

It should Never be used in modern code since it makes code very difficultto maintain.

It is mostly used to force a termination of heavily nested code, where thelogic to safely exit would be tortuous.

Never jump into or out of try statements, or into a loop or conditionalblock.

Be careful! Use with extreme caution and only when fully justified.

CSCI 6636 – 4536 Lecture 6. . . 12/39 March 10, 2020 12 / 39

Page 13: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Goto Statements

Why goto Statements are Obsolete

Using a goto is no longer good practice because it has bad effects on:

Translation: the compiler must remember the location of all statementlabels for the scope of the program, just in they are needed. Tocompile a goto statement, the compiler must search the list of labels.Modularity: all parts of the program between the goto and the targetbecome part of one module. This breaks or confuses modern ideas ofmodularity.Debug-ability: using goto’s makes it much harder to trace a program’slogic, and therefore hard to debug.Maintainability: for the same reason, it is harder to modify or maintain.

With the introduction of break, continue, and exceptions, there is nolonger a need for goto’s.

CSCI 6636 – 4536 Lecture 6. . . 13/39 March 10, 2020 13 / 39

Page 14: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Goto Statements

New Kinds of Spaghetti Code

All major languages developed after C implement, tweak, and extend the Ccontrol structures, and support exceptions. Goto’s are uniformly frownedupon, but still there. However, we now have a variety of ways to makespaghetti code without using goto.

The term spaghetti code is now used to describe any program where thepath of execution is not clear from the appearance of the code, and a flowchart is needed to figure out the logic.

You can write spaghetti code using “structured units” if you include deeplynested logic units controlled by multiple state variables (boolean or not).And it is still poor technique.

CSCI 6636 – 4536 Lecture 6. . . 14/39 March 10, 2020 14 / 39

Page 15: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control What Kinds of Control are Needed?

Minimal Necessary Control

Jacopini and Boehm proved that the if...then...else, while,and statement sequences form an adequate basis for programmingwithout goto’s.

Procedural languages are built on this foundation.

But you do not need all of these control structures:if...then...else and recursion (replacing loops and sequences)form an adequate basis for a language. Functional languages are builton this foundation.

The pure functional languages are built on this foundation and do notneed or support sequences or loops.

CSCI 6636 – 4536 Lecture 6. . . 15/39 March 10, 2020 15 / 39

Page 16: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control What Kinds of Control are Needed?

Structured vs. Unconstrained Control

The control capabilities built into a language can be structured orunconstrained.

A goto statement or expression is unconstrained: It can go to a targetanywhere.

An if...then...else statement or a while loop is structured: ithas a defined beginning and end, and control flows through it in aprescribed way.

Function calls are structured control because a call defines acontrolled interface between two parts of a program, and controlreturns to the point at which the call started.

Exceptions and break statements are structured because they can onlyend up at defined spots in the program.

CSCI 6636 – 4536 Lecture 6. . . 16/39 March 10, 2020 16 / 39

Page 17: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control What Kinds of Control are Needed?

Minimal necessary control

To avoid using goto’s, a set of structured control is required in a computerlanguage language: the programmer needs a way to write conditional codeand to repeat blocks of code.

if...then...else and recursion form a minimal adequate basis fora language. Functional languages are built on this foundation.

if...then...else, the while loop and statement sequences alsoform an adequate basis for programming. Procedural languages arebuilt on this foundation.

However, many languages of both sorts provide a wide assortment ofother control structures for convenience and program clarity.

Note: A simple if, without the possibility of an else clause is not anadequate basis for defining a language.

CSCI 6636 – 4536 Lecture 6. . . 17/39 March 10, 2020 17 / 39

Page 18: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Structured Control

Structured Control

ConditionalsLoops

Exceptions

These are familiar today to every programmer. The goal here is tounderstand the variations, the details, the design decisions, and what acompiler does with the control statement.

CSCI 6636 – 4536 Lecture 6. . . 18/39 March 10, 2020 18 / 39

Page 19: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Conditionals

Variations on the Conditional

An easy way to start learning a new language is to find out how to writeexpressions, statements, and simple and multi-way conditionals. This iseasy because all languages are very much alike in this area. However, thereare lots of minor variations:

Keywords vary: if, cond, WHEN, then, switch, EVALUATE

else, elseif, elif, case

The method of delimiting the three clauses varies: parentheses,brackets, case labels, keywords (then, elif, elseif, endif)

There can be one test per possible action to execute (as in LISPcond) or one test altogether, followed by a sequence of severalpossible clauses, which will be selected based on the outcome of thetest (as in a C switch).

After an action is selected and executed, control normally goes to theend of the conditional unit. ( The C switch is poorly designedbecause a separate break is needed to do this.)

CSCI 6636 – 4536 Lecture 6. . . 19/39 March 10, 2020 19 / 39

Page 20: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Conditionals

Simple Conditional Semantics

A simple conditional statement consists of a test followed by two sets ofactions (clauses).

The first clause (the then clause) is used when the test result is true.

The second clause (the else clause) is executed when the result isfalse.

A conditional statement must be evaluated outside-in.

The condition must be evaluated first.

The result of the condition is then tested and used to select either thethen clause or the else clause. One or the other will be executed,but never both.

The outside-in evaluation lets us write guarded expressions which avoidexecuting infinite loops or computations that would crash the program.

CSCI 6636 – 4536 Lecture 6. . . 20/39 March 10, 2020 20 / 39

Page 21: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Conditionals

Multi-way Conditionals-1

A multiway conditional has more than two clauses following the test.

A cond in Lisp and Scheme is a series of (test action) pairs.

The conditions are evaluated top-to-bottom. The action selected isthe one following the first test that returns true.

This is similar to the if..elseif..else in Fortran, the if..elsif..else in Ada,and the if..elif..else in Python.

The same semantics is achieved in C with fewer keywords by nestingsimple if statements and using braces to delimit clauses.

CSCI 6636 – 4536 Lecture 6. . . 21/39 March 10, 2020 21 / 39

Page 22: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Conditionals

Multi-way Conditionals-2

The C switch and the Ada case illustrate a different multi-way semantics:

There is only one test expression at the top,

Followed by multiple pairs, each pair consisting of one or more caselabels and a set of actions.

The case labels are integer or enumerated constants.

A well-designed version has an optional default clause at the end.

To execute a switch, the test expression is evaluated and the resultingvalue is compared to the case labels. If one matches, thecorresponding action is selected.

Reasonably clean programs can be built without the multi-wayconditionals. They are common in languages, though, because they oftenprovide a better way to model complex decision-making.

CSCI 6636 – 4536 Lecture 6. . . 22/39 March 10, 2020 22 / 39

Page 23: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Conditionals

Compiling a Conditional

if (test)

True Action(s)

False Action(s)

on false, go to y

go to z

z

y

next line of code

During code generation, the compilerworks on the fully parsed program. Tocompile a simple conditional, it mustinsert a conditional jump and anunconditional jump into the code.

When the conditional jump must begenerated, the compiler does not knowhow far ahead to go. So it remembers theaddress of the unfinished jump instruction.

At the end of the true actions, anincomplete unconditional forward jump isgenerated.

The next address becomes the target for the conditional jump.

After compiling the false actions, the second jump is completed withaddress z.

CSCI 6636 – 4536 Lecture 6. . . 23/39 March 10, 2020 23 / 39

Page 24: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Repetition

Loops vs. Recursion

A programming language needs a way to specify repetition.

This could be done using recursion.

It could be done using loops.

Modern languages usually support both kinds of repetition, in oneway or another.

Generally, a loop is faster than a recursion to do the same thing.

Often, a recursion is more concise than a loop.

CSCI 6636 – 4536 Lecture 6. . . 24/39 March 10, 2020 24 / 39

Page 25: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Repetition

Loop Statements

A loop statement executes a process that changes memory and/orproduces a side-effect.

A for-each loop applies an action to every element of an array or list.

The general loop (FORTH and C) has a body of code with an exittest potentially anywhere within that body.

Restricted loops have an exit test at the top (while) or at the bottom(do . . . while).

Counted loops execute a block of code the number of times specifiedby the control code. Depending on the language, this can becomputed at the beginning of the loop or remain flexible throughoutthe loop.

We do not need all these loops to write clean, structured programs. Theyexist because they are useful ways to describe program logic. d

CSCI 6636 – 4536 Lecture 6. . . 25/39 March 10, 2020 25 / 39

Page 26: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Repetition

Compiling a While Loop

while (test)

Loop Action(s)

on false, go to z

go to xz next line of code

x

To compile a loop, the compiler mustinsert a conditional forward jump after theloop test and an unconditional backwardjump at the bottom.

At the time the conditional jump must begenerated, the compiler does not knowhow far ahead to go. So it remembers theaddress of the unfinished jump instruction.

When it comes to the end of the loopactions, it generates an unconditionalbackward jump to the loop test.

Then it uses the next machine address asthe target for the incomplete conditionaljump.

CSCI 6636 – 4536 Lecture 6. . . 26/39 March 10, 2020 26 / 39

Page 27: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Repetition

Compiling a General Loop

Some programs (for example, servers) run an explicit infinite loop. In suchloops, there is no exit test at all. This is one-in-zero-out control.

Far more common are situations that call for processing both before andafter the loop test. Examples include the need for an eof test after readinginput and before processing it.

Loop Action(s)

Loop Actions(s)

z next line of code

x

go to x

if (test) goto z on true

Iin these loops, the loop test can appearanywhere in the body of the loop. It isimplemented using if. . . break logic.

As with a restricted loop, a conditionalforward jump and an unconditionalbackward jump are required. Both mustbe generated in an incomplete form andpatched later.

CSCI 6636 – 4536 Lecture 6. . . 27/39 March 10, 2020 27 / 39

Page 28: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Repetition

Counted Loops

Counted loops differ more in syntax and semantics, from language tolanguage, than any other kind of control structure.

The biggest issue is whether there is a constant tripcount,calculated once before repetition begins. That is, whether therequired number of repetitions of the loop body can be changed bysomething in the body of the loop.

Two factors can make the tripcount unpredictable:

Can the exit condition be changed within the loop, or is it constant?Can the loop variable be changed by the loop body, or only by thecontrol clause?

A predictable tripcount makes the task of the compiler and the workat runtime minimally easier. There is a much larger effect, however,on the clarity and debug-ability of the program.

C’s for loop is extreme: totally flexible and much more prone torun-time surprises and gotchas.

CSCI 6636 – 4536 Lecture 6. . . 28/39 March 10, 2020 28 / 39

Page 29: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Repetition

Compiling a Counted Loop

Loop Action(s)

Increment

on false, go to z

go to xz

Conditiony

next line of code

xgo to y

To compile a loop, it must insert aconditional forward jump after the looptest and an unconditional backward jumpat the bottom.

At the time the conditional jump must begenerated, the compiler does not knowhow far ahead to go. So it remembers theaddress of the unfinished jump instruction.

When it comes to the end of the trueactions, it generates an incompleteunconditional forward jump.

It uses the next available address as the jump target for the first one.

After generating code for the false actions, it discovers address z andgoes back to patch the incomplete unconditional jump.

CSCI 6636 – 4536 Lecture 6. . . 29/39 March 10, 2020 29 / 39

Page 30: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Exceptions

Exceptions

Long after structured programming became the accepted proceduralparadigm, goto statements were still needed, possibly 1% of the time.Important applications were:

Error handling that could not be done locally.

Escape from the bottom levels of a deeply nested control structure.

Exceptions became part of most major languages by the mid-90’s,although some hardware platforms failed to support them completely.

CSCI 6636 – 4536 Lecture 6. . . 30/39 March 10, 2020 30 / 39

Page 31: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Structured Control Exceptions

Implementation Difficulties

All stack frames from the one that throws the exception to thecontext that handles it must be removed from the runtime stack.

The exception cannot be allocated on the stack, because the stackwill be unwound. Therefore, In C++, an exception is a system objectand both allocation and deallocation are handled by the system.

The major theoretical problem involved is how to handle resources(dynamic allocation, locks, open files) that belong to the intermediatestack frames when control makes a superman-jump from the contextthat threw the exception to an earlier context that could handle it.

In Java, this is handled by finally clauses. This system is known to bea major contributing factor to software bugs when the software dealswith multiple resources.

In C++, the problem is handled by running the destructors for allobjects in the dying stack frames. This works reliably if programmerswrite correct destructors.

CSCI 6636 – 4536 Lecture 6. . . 31/39 March 10, 2020 31 / 39

Page 32: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions

Control Expressions

The Functional PhilosophyConditional Expressions

Loop Expressions

CSCI 6636 – 4536 Lecture 6. . . 32/39 March 10, 2020 32 / 39

Page 33: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions

Expressions vs. Statements

All programming languages have control elements that allow testing andrepetition.

In statement-based languages, these are usually control statements

In functional languages, these are usually control expressions orfunctions

Some languages support both but rely more heavily on one or theother.

CSCI 6636 – 4536 Lecture 6. . . 33/39 March 10, 2020 33 / 39

Page 34: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions

The Functional Philosophy

Names and Values:

A name is either undefined, or it has a single, immutable meaning.(No mutators, no assignment.)

The type of a value can be deduced from the value itself. (It startswith some sort of a type tag.)

Functions:

A function should depend only on its parameters and its own logic.

It should not change anything outside its scope.

Given the same parameters, the result should always be the same.

A function IS an object and can be a parameter to or result ofanother function.

CSCI 6636 – 4536 Lecture 6. . . 34/39 March 10, 2020 34 / 39

Page 35: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions

Functional Principles

State:

The state of a computation is entirely determined by the set ofparameters in use on the stack. There is no global state.

Types:

Objects have types; variable names don’t.

Control:

Control is done through expressions, not statements. Statements donot exist.

CSCI 6636 – 4536 Lecture 6. . . 35/39 March 10, 2020 35 / 39

Page 36: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions

Order of Execution

Pure functional languages (ML, Haskell) use lazy evaluationthroughout.

As a result of laziness, the sequence in which lines of code are writtenis not the same as the order in which they are evaluated. (Anapparent statement sequence is an illusion–the results would be thesame if the lines were scrambled.)

Instead, evaluation order is determined by how function calls arenested in the code, and by whether local variables and parameters areused at all.

Parameter binding is the primary means naming a value.

Functional languages use dynamic binding (no declarations) to attachnames to objects, and allow only one binding during the lifetime ofthe name.

CSCI 6636 – 4536 Lecture 6. . . 36/39 March 10, 2020 36 / 39

Page 37: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions Conditional Expressions

Conditional Expressions

A conditional expression makes a test and returns a value. It can thereforebe used in the middle of any expression, including another conditionalexpression.

The conditional expression was supported by Algol-60.

C’s conditional expression is<test> ? <true-action> : <false-action> Java and C#

share this syntax.

Algol-60 and Python have analogous forms.

Scheme and Lisp provide not-quite-identical versions of cond

Haskell and Miranda provide guarded expressions.

CSCI 6636 – 4536 Lecture 6. . . 37/39 March 10, 2020 37 / 39

Page 38: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Control Expressions Conditional Expressions

Loop Expressions

A loop expression evaluates a function repeatedly and calculates ananswer, or iterates down an array or list, producing a result that is anumber or another array or list.

In Scheme: map operates on lists and produces a list as its result.(map 1+ (list 1 2 3 4 5))

;Value 2: (2 3 4 5 6)

In APL any function can be applied to an array and produce an array:A← 1 2 3 4 5 B ← 2 3 ρ ι 6A + 1 B × 2

2 3 4 5 6 2 4 68 10 12

These control expressions can accomplish in one line what the usualcontrol statements take several lines to do.

CSCI 6636 – 4536 Lecture 6. . . 38/39 March 10, 2020 38 / 39

Page 39: Structure of Programming Languages Lecture 6eliza.newhaven.edu/lang/attach/L6-Control.pdfOne-in / one-out control structures became sacred cows: essential to avoid \spaghetti code"

Homework

HomeworkRead Chapters 8 and 10 of the text.

1 This expression can be evaluated inside-out or outside in:x=sqrt( 3*z - floor(y))

Which function is called first in an inside-out evaluation? Which iscalled first in an outside-in evaluation?

2 What is the difference between a conditional statement and aconditional expression? Note that a conditional expression is NOTwhat you might write in the parentheses of a while statement.

3 What restrictions that are necessary in a C for loop to ensure that youcan predict the tripcount ahead of time.

4 List the jump statements (things like break, continue, goto, andexceptions) that are supported in Ruby. Explain how each one works.

5 After reading the relevant section in the text, explain why unrestrictedcontrol statements (goto) make it difficult to translate and maintain alarge program.

CSCI 6636 – 4536 Lecture 6. . . 39/39 March 10, 2020 39 / 39