Download presentation

Presentation is loading. Please wait.

1
**Prof. Dr. Max Mühlhäuser Dr. Guido Rößling**

Introduction to Computer Science I Topic 1: Basic Elements of Programming Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

2
What is Programming? Let us take a look at what some godfathers of programming have to say: „To program is to understand“ Kristen Nygaard „Programming is a Good Medium for Expressing Poorly Understood and Sloppily Formulated Ideas“ Marvin Minsky, Gerald J. Sussman

3
**The Elements of Programming**

A powerful programming language (PL) is more than just a means for instructing a computer to perform tasks It also serves as a framework within which we organize our ideas about a problem domain When we describe a language, we should pay attention to the means that it provides for combining simple ideas to more complex ones.

4
**The Elements of Programming**

Every powerful language has three mechanisms to structure ideas about processes: Primitive expressions Represent the simplest entities of the language Means of combination Compound elements are built from simpler ones Means of abstraction Compound elements can be named and manipulated as units

5
**Keys to Engineering Design**

Primitives Resistors, capacitors, inductors, voltage sources, … Means of combination Rules for how to wire together in a circuit Standard interfaces (e.g. voltages, currents) between elements Means of abstraction “Black box” abstraction – think about sub-circuit as a unit: e.g. amplifier, modulator, receiver, transmitter, …

6
**Language Elements - Primitives**

Numbers Examples: 23, -36 Numbers are self-evaluating: the values of the digits are the numbers they denote 23 → → -36 Boolean values true and false Also self evaluating Names for built-in procedures Examples: +, *, /, -, =, … What is the value of such an expression? The value of + is a procedure We will later refer to these kinds of values as “first-class procedures” Evaluating by looking up the value associated with the name

7
**(+ 2 3) Compound Elements left parenthesis right parenthesis Operator**

Operands prefix notation The value of a compound element is determined by executing the procedure (denoted by the operator) with the values of the operands. Vorteile der Präfix Notation …

8
**(+ 2 3) Compound Elements Compound Elements: Example: left parenthesis**

A sequence of expressions enclosed in parentheses the expressions are primitives or compounds themselves Example: Expressions representing numbers may be combined with expressions representing a primitive procedure (+ or *) to form a compound expression represents the application of the procedure to the numbers (+ 2 3) left parenthesis Operator Operands right parenthesis Vorteile der Präfix Notation …

9
**Compound Elements (+ 4 (* 2 3)) = (4 + (2 * 3)) = 10**

Can use nested combinations just apply rules recursively (+ 4 (* 2 3)) = (4 + (2 * 3)) = 10 (* (+ 3 4) (- 8 2)) = ((3 + 4) * (8 - 2)) = 42 A combination always denotes a procedure application parentheses cannot be inserted or omitted without changing the meaning of the expression

10
Abstractions Create a complex thing by combining more primitive things, name it, treat it like a primitive. Simple mean of abstraction: define (define score (+ 23 7)) (define PI 3.14)

11
**Naming Compound Elements**

Special form: A bracketed expression, starting with one of the few keywords of scheme Example: define using define we can pair a name with a value example: (define score (+ 23 7)) The define special form does not evaluate the second expression (in the example: score) Rather, it pairs that name with the value of the third expression in an environment The return value of a special form is unspecified

12
**Naming and the Environment**

An important aspect of a programming language is the means it provides to refer to computational objects using names. A name identifies a variable whose value is the object Environment: the interpreter maintains some sort of memory to keep track of the name-object pairs. Associating values with symbols Retrieve them later

13
**Naming and the Environment**

To get the value of a name, just look it up in environment Example: the evaluation of score is 30 (define score (+ 27 3)) (define total ( )) (* 100 (/ score total)) Note: we already did this implicty (looking up a name in an environment) for +, *, … + * / … 30 score 25 total

14
**Evaluation Rules Self evaluating return the value**

The values of digits are the numbers that they name Built-in operator return the machine instruction sequence that carry out the corresponding operations. Name return the value that is associated with that name in the environment. Special form do something special. Combination Evaluate the sub expressions (arbitrary order) Apply the procedure that is the value of the leftmost sub expression (the operator) to the arguments that are the values of the other sub expressions (the operands). Example of a combination: (+ 4 (* 2 3)) Selbst komplexe Ausdrucke bearbeitet der Interpreter nach Grundzyklus Interpreter muss nicht explizit angewiesen werden, den Wert des Ausdrucks auszugeben Die Regel 2 kann als spezial fall von 3 betrachtet werden Betonne die Schlüsselrole der Umgebung für die Auswertung Hebe die Sonderformen hervor

15
**Evaluating Combinations**

The evaluation rule is recursive as one of its steps, the rule needs to invoke itself Every element has to be evaluated before the whole evaluation can be done Evaluating the following combination requires that the evaluation rule be applied to 4 different combinations. ( * (+ 2 (* 4 6) ) ( ) )

16
**Read-Eval-Print-Loop**

define-rule: Only evaluate the second operand The name of the first operand is bound to the calculated value The overall value of the expression is undefined print Differences between Scheme versions (define PI 3.14) eval define-rule ”PI --> 3.14" Visible world Execution world Name Value undefined PI 3.14

17
**Read-Eval-Print-Loop**

printed representation of the value Expression Expression 23 23 PI 3.14 eval name-rule print Visible World print calculate self-rule Execution World 23 Value Value Naming-rule: Look-up the value in the current environment using the name

18
**Capturing common patterns**

Here are some common patterns (* 3.14 (* 5 5)) (* 3.14 (* )) (* 3.14 (* x x)) How do we generalize (e.g. the last expression)? i.e. how to express the idea of “circle area computation”? They are instances of a circle area computation Kurze Wiederholung der bis hier Besprochenes Prozedurdefinition als eine weitaus leistungsfähigere Abstraktionsmittel: Eine zusammengesetzte Operation einen Namen geben mit dem man auf sie sich beziehen kann.

19
**Creating new procedures**

We use procedures to capture ways of doing things sometimes we also use the name function similar to a function in mathematics The define special form is used to create new procedures Name Parameter (define (area-of-disk r) (* 3.14 (* r r))) Body of procedure

20
**Creating new Procedures**

As soon as a procedure has been defined, we can use it as if it were a primitive procedure (such as +, * etc.) Example - area of a circle: (area-of-disk 5) = 78.5 Example - area of a ring: (- (area-of-disk 5) (area-of-disk 3)) = ( ) = 50.24 - =

21
**Creating new procedures**

Existing procedures can be combined to new, more powerful procedures Example: calculate area of a ring Example: Using the new procedure (area-of-ring 5 3) = (- (area-of-disk 5) (area-of-disk 3)) = (- (* 3.14 (* 5 5)) (* 3.14 (* 3 3))) = … = 50.24 (define (area-of-ring outer inner) (- (area-of-disk outer) (area-of-disk inner)))

22
**Informal specifications**

Typical program specification Usually not in mathematical terms that can be directly transformed into programs Often rather informal problem specifications May contain irrelevant or ambiguous information Example: “Company XYZ & Co. pays all its employees $12 per hour. A typical employee works between 20 and 65 hours per week. Develop a program that determines the wage of an employee from the number of hours of work.” problem analysis (define (wage hours) (* 12 hours))

23
**Errors Your programs will contain errors Possible errors:**

This is normal Don’t get confused or frustrated by your errors Possible errors: Wrong number of brackets, i.e. (* 3 (5) The operator of a procedure call is not a procedure (10) ( ) other typical runtime errors: (+ 3 true) (/ 3 0) Try out what is happening in erroneous programs and try to understand the error message!

24
**Designing Programs The design of programs is not trivial**

The following design recipe helps you in writing your first program: step-by-step prescription of what you should do Later we will refine this recipe Any program development requires at least the following four activities: Understanding the program's purpose Thinking about program examples Implementing the program body Testing

25
**“If you can't write it down in English, you can't code it.“**

Designing Programs “If you can't write it down in English, you can't code it.“ Peter Halpern Understanding the program's purpose calculate the area of a ring: calculate the area of the ring that has an outer radius ‘outer’ and an inner radius ‘inner’ It can be calculated using the radius of the circle with radius ‘outer’ and subtracting the area of the circle with radius ‘inner’ …

26
**Designing Programs Understanding the program's purpose**

Giving the program a meaningful name Definition of a contract What kind of information is consumed and produced? Adding the program header Formulate a short purpose statement for the program, that is a brief comment of what the program is to compute ;; area-of-ring :: number number -> number ;; ;; to compute the area of a ring, ;; whose hole has a radius of “inner” (define (area-of-ring outer inner) … )

27
**Designing Programs Program Examples**

Help to characterize the input and output Examples help us to understand the computational process of a program and to discover logical errors It is easier to understand something difficult with an example For our example: ;; area-of-ring :: number number -> number ;; to compute the area of a ring, ;; whose hole has a radius of “inner” ;; Example: (area-of-ring 5 2) is 65.94 (define (area-of-ring outer inner) … )

28
**Designing Programs Implement the program body**

Replace the “...” in our header with an expression If the input-output relationship is given as a mathematical formula, we just translate In case of an informally stated formula, we have to understand the computational task the examples of step 2 can help us ;; area-of-ring :: number number -> number ;; to compute the area of a ring, ;; whose hole has a radius of “inner” ;; Example: (area-of-ring 5 2) is 65.94 (define (area-of-ring outer inner) (- (area-of-disk outer) (area-of-disk inner)))

29
**Designing Programs 4. Testing i.e. with the DrScheme Testcases**

(Special -> Insert Testcase) to discover mistakes in particular for non local errors

30
**“Testing can show the presence of bugs, but not their absence.”**

Edsger W. Dijkstra “Beware of bugs in the above code; I have only proved it correct, not tried it“ Donald E. Knuth

31
**Auxiliary Functions When should we use auxiliary functions? Example:**

The owner of a performance theater wants you to design a program that computes the relationship between profit and ticket price At a price of 5€ per ticket, 120 people attend a performance. Decreasing the price by 0.10€ increases attendance by 15 people. Each performance costs the owner 180€. Each attendee costs 0.04€.

32
**Auxiliary Functions: Bad Design**

;; How NOT to design a program (define (profit price) (- (* (+ 120 (* (/ ) ( price))) price) (+ 180 (* .04 (+ 120 ( price)))))))

33
**Auxiliary Functions: Good Design**

;; How to design a program (define (profit ticket-price) (- (revenue ticket-price) (cost ticket-price))) (define (revenue ticket-price) (* (attendees ticket-price) ticket-price)) (define (cost ticket-price) (+ 180 (* 0.04 (attendees ticket-price)))) (define (attendees ticket-price) (+ 120 (* 15 (/ ( ticket-price) 0.10))))

34
**Guideline on Auxiliary Functions**

Formulate auxiliary function definitions for every dependency between quantities mentioned in the problem statement or quantities discovered with example calculations.

35
**Procedures as Black-Box-Abstractions**

Abstraction helps hiding complexity Details that are irrelevant for understanding from a special point of view are ignored.

36
**Procedures as Black-Box abstractions**

Will consider several fundamental kinds of abstraction in this course. Procedural abstraction is one: area-of-ring computes the area of a ring user doesn't have to think about the internals black-box-abstraction Input Output We know what it does, but not how.

37
**Procedures as Black-Box abstractions**

A computing problem is often broken down into natural, smaller sub-problems. Example: area of a ring 2* Calculating the area of a circle Procedures are written for each of these sub problems. area-of-disk,… primitive procedures …

38
**Procedures as Black-Box abstractions**

The procedure attendees can be seen as black box. We know that it calculates the number of attendees. But we do not want to know how it works. These details can be ignored. attendees is a procedural abstraction for revenue/cost. profit revenue cost attendees

39
**Procedures as Black-Box abstractions**

A user defined procedure is called by a name, as are primitive procedures How a procedure works remains hidden. area-of-ring area-of-circle square At this level of abstraction, any procedure that calculates squares is as good as any other. (define (square x) (* x x)) (define (square x) (* (* x 10) (/ x 10)))

40
**constant definition Guideline on Variable Definitions:**

Better to read Easier to maintain changes must be made at one point only In our example: (define PI 3.14) We only need one change for a better approximation (define PI ) Give names to frequently used constants and use the names instead of the constants in programs

41
**Conditional Expressions**

Two modes: 1) (if <test> <then-expr> <else-expr>) not optional in Scheme Example: (define (absolute x) (if (< x 0) (- x) x))

42
**Conditional Expressions**

Two modes: 2) (cond [<test1> <expr1>] [<test2> <expr2>] [else <last-expr>]) optional Example: (define (absolute x) (cond [(> x 0) x] [(= x 0) 0] [else (- x)])) Eigentlich habe ich gelogen. Der <else-expr> Ausdruck in if Anweisung und in dem else Zweig in cond Anweisungen sind optional, aber der Rückgabewert ist nicht spezifiziert, also lassen Sie es besser nicht aus.

43
**Comments on conditionals**

A test is „true“ if the evaluation is true A branch of a cond can have more than one expression: (<test> <expr1> <expr2> <exprN>) As long as we have no „side effects“, we do not need more than one expression (<test>) returns value of <test> The else branch must contain at least one expression

44
Boolean functions (and <expr_1> <expr_2> <expr_N>) <expr_i> (i = 1..N) evaluated in order of appearance; returns false if any expression is evaluated to false, else the return is true (shortcut). If one of the expressions returns neither true or false, then an error will occur. Some expressions will not be evaluated due to the shortcut-Rule (and (= 4 4) (< 5 3)) false (and true (+ 3 5)) Error: and: question result is not true or false: 8 (and false (+ 3 5)) Shortcut-Rule: false

45
Boolean functions (or <expr_1> <expr_2> <expr_N>) <expr_i> (i = 1..N) evaluated in order of occurrence; returns true after the first value is evaluated to true; returns false if all expressions are false An error occurs if a value evaluates to neither true or false (or (= 4 4) (< 5 3)) true (or true (+ 3 5)) Shortcut-Rule: true (or false (+ 3 5)) Error: or: question result is not true or false: 8

46
**Boolean functions (boolean=? <expr1> <expr2>)**

expr1, expr2 evaluated in order of appearance; returns true, if expr1 and expr2 both produce true or both produce false returns false, if the operands have different Boolean values an error occurs, if an operand evaluates to neither true or false (not <expr>) returns true when <expr> evaluates to false returns false when <expr> evaluates to true Füge Tabellen hier

47
**Designing Conditional Functions**

How does our design process change? New Phase: Data analysis Which different situations exist? Examples choose at least one example per situation Implementing the program body First write down the skeleton of a cond/if expression, then implement the individual cases Testing tests should cover all situations Program development requires at least the following four activities Understanding the program's purpose Making up examples Implementing the program body Testing

48
Symbols Up to this point, we know numbers and Booleans as primitive values Often we want to store symbolic information names, words, directions A symbol in Scheme is a sequence of characters, headed by a single quotation mark: ‘the ‘dog ‘ate ‘a ‘cat! ‘two^3 ‘and%so%on? Not all characters are allowed (i.e. no space) Only one operation on this data type: symbol=? (symbol=? ‘hello ‘hello) true (symbol=? ‘hello ‘abc) false (symbol=? 1 2) error Symbols are atomic (like numbers, Booleans) Symbols cannot be separated

49
**Symbols: Example (define (reply s) (cond**

[(symbol=? s 'GoodMorning) 'Hi] [(symbol=? s 'HowAreYou?) 'Fine] [(symbol=? s 'GoodAfternoon) 'INeedANap] [(symbol=? s 'GoodEvening) 'BoyAmITired] [else 'Error_in_reply:unknown_case] ))

50
**Symbols vs. Strings Many of you may know the data type String**

Symbols are different from Strings Symbols: Are used for symbolic names atomic, no manipulation, very efficient comparison certain restrictions which characters can be represented Strings: Are used for text data Manipulation possible (i.e. search, compose etc.) Comparison is expansive Any kind of character (string) is possible Strings are also available in Scheme To generate with a double quotation mark; compare with string=? For now we will ignore strings

51
**Reminder: The Evaluation-Rule**

Up to now we have only considered built-in procedures. How to evaluate procedures that are defined by the programmer? self evaluated … built-in operator … Name … special form … Combination Evaluate the sub expressions (in any order) Apply the procedure that is the value of the leftmost sub expression (the operator) to the arguments that are the values of the other sub expressions (the operands).

52
**Extended Evaluation-Rule**

Evaluation rule for procedures The procedure is a primitive procedure execute the respective machine instructions. The procedure is a compound procedure Evaluate the procedure body Substitute each formal parameter with the respective actual value, that is passed when applying the procedure. (define (f x ) (* x x)) (f 5 )

53
**Declaring the formal parameters**

Substitution Model Fictive names (formal parameters/variables): allow the definition of general procedures that can be reused in various situations. When using the procedures, the actual values need to be associated with the fictive names. As known from algebra: f(a, b) = a2 + b2 Declaring the formal parameters Defining the function using formal parameters Using the general function to solve a particular problem f (3, 2)

54
**Substitution Model a b ... (define b 2) ... (f 3 2) ...**

Associating the actual values when executing (define (f a b) (+ (* a a) (* b b))) a b ... (define b 2) ... (f 3 2) ... ... (f b 2) ... ... a * a b * b + Calling environment Procedure environment of f

55
**Substitution Model a 3 2 b ... (define b 2) ... (f 3 2) ...**

Associating the actual values when executing (define (f a b) (+ (* a a) (* b b))) a 3 2 b ... (define b 2) ... (f 3 2) ... ... (f b 2) ... ... a * a 3 * 3 b * b 2 * 2 + 13 Calling environment Procedure environment of f

56
**Substitution Model 2 a b 2 ... (define b 2) ... (f 3 2) ...**

Associating the actual value when executing 2 a b 2 ... (define b 2) ... (f 3 2) ... ... (f b 2) ... ... 2 * 2 a * a b * b 2 * 2 + 8 Calling environment Procedure environment of f

57
Substitution Model The purpose of the substitution model is to help us think about procedure application It does not provide a description of how the interpreter really works Typically, an interpreter does not evaluate procedure applications by manipulating the text of a procedure to substitute values for the formal parameters. This is a simplified model to get started thinking formally about the evaluation process More detailed models will follow later on Allows you to “execute” a program on a piece of paper

58
**Details of the Substitution Model: applicative order of evaluation**

(define (square x) (* x x))) (define (average x y) (/ (+ x y) 2))) (average 5 (square 3)) (average 5 (* 3 3)) (average 5 9) first evaluate the operands, then do the replacement (applicative order) (/ (+ 5 9) 2) (/ 14 2) If the operator is a simple procedure, replace it 7 with the result of the operation

59
**Details of the Substitution Model: normal order of evaluation**

(define (square x) (* x x)) (define (average x y) (/ (+ x y) 2)) (average 5 (square 3)) (/ (+ 5 (square 3)) 2) (/ (+ 5 (* 3 3)) 2) (/ (+ 5 9) 2) (/ 14 2) 7 normal order

60
**Applicative vs. normal order of evaluation**

Applicative: First evaluate the operator and all operands, then substitute Normal: Evaluate operator, then substitute the (not evaluated) operands for the formal arguments of the operator Important, non-trivial property: The result does not depend on the order of evaluation (confluence) However, termination of the evaluation process may depend on the evaluation order We will see features (assignment, in-/output) which destroy this characteristic later Sometimes both strategies can be very different in the number of evaluation steps argument is not required normal order wins argument is required several times applicative order wins

61
**Review: Scheme Things that constitute a Scheme program: Syntax**

self evaluating 23, true, false, names +, PI, pi combinations (+ 2 3) (* pi 4) special forms (define PI 3.14) Syntax combination: (oper-expression other-expressions …) special form: a special keyword as first sub routine Semantics combinations: evaluate subroutines in any order, use the operator for the operands substitution for user-defined procedures special forms: each form has its own

62
**Summary We have learned:**

The simplest elements (data/procedures) of Scheme Combination as a composing instrument of simpler elements into more complex elements How to make combinations to use them further as elements in other combinations How to define own procedures – process pattern – and use them as basic elements of combinations _______________________ Scheme ________________________ Separate problems to smaller exact defined tasks Procedures as Black-Box abstraction Semantic of a procedure call as a substitution process

Similar presentations

Presentation is loading. Please wait....

OK

口算小能手.

口算小能手.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on series and parallel circuits Sayings we share ppt online Ppt on history of olympics in united Ppt on image demosaicing process Ppt on nutrition in plants Ppt on central administrative tribunal Std ppt only Ppt on introduction to object oriented programming Save ppt on ipad Ppt on forest conservation act