Presentation on theme: "Prof. Dr. Max Mühlhäuser Dr. Guido Rößling"— Presentation transcript:
1Prof. Dr. Max Mühlhäuser Dr. Guido Rößling Introduction to Computer Science I Topic 1: Basic Elements of ProgrammingProf. Dr. Max Mühlhäuser Dr. Guido Rößling
2What 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
3The Elements of Programming A powerful programming language (PL) is more than just a means for instructing a computer to perform tasksIt also serves as a framework within which we organize our ideas about a problem domainWhen we describe a language, we should pay attention to the means that it provides for combining simple ideas to more complex ones.
4The Elements of Programming Every powerful language has three mechanisms to structure ideas about processes:Primitive expressionsRepresent the simplest entities of the languageMeans of combinationCompound elements are built from simpler onesMeans of abstractionCompound elements can be named and manipulated as units
5Keys to Engineering Design PrimitivesResistors, capacitors, inductors, voltage sources, …Means of combinationRules for how to wire together in a circuitStandard interfaces (e.g. voltages, currents) between elementsMeans of abstraction“Black box” abstraction – think about sub-circuit as a unit: e.g. amplifier, modulator, receiver, transmitter, …
6Language Elements - Primitives NumbersExamples: 23, -36Numbers are self-evaluating: the values of the digits are the numbers they denote 23 → → -36Boolean valuestrue and falseAlso self evaluatingNames for built-in proceduresExamples: +, *, /, -, =, …What is the value of such an expression?The value of + is a procedureWe 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 Operandsprefix notationThe 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 parenthesesthe expressions are primitives or compounds themselvesExample:Expressions representing numbers may be combined with expressions representing a primitive procedure (+ or *) to form a compound expressionrepresents the application of the procedure to the numbers(+ 2 3)left parenthesisOperatorOperandsright parenthesisVorteile der Präfix Notation …
9Compound Elements (+ 4 (* 2 3)) = (4 + (2 * 3)) = 10 Can use nested combinationsjust apply rules recursively(+ 4 (* 2 3)) = (4 + (2 * 3)) = 10(* (+ 3 4) (- 8 2))= ((3 + 4) * (8 - 2))= 42A combination always denotes a procedure application parentheses cannot be inserted or omitted without changing the meaning of the expression
10AbstractionsCreate 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)
11Naming Compound Elements Special form: A bracketed expression, starting with one of the few keywords of schemeExample: defineusing 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 environmentThe return value of a special form is unspecified
12Naming 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 objectEnvironment: the interpreter maintains some sort of memory to keep track of the name-object pairs.Associating values with symbolsRetrieve them later
13Naming and the Environment To get the value of a name, just look it up in environmentExample: 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 +, *, …+*/…30score25total
14Evaluation Rules Self evaluating return the value The values of digits are the numbers that they nameBuilt-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 GrundzyklusInterpreter muss nicht explizit angewiesen werden, den Wert des Ausdrucks auszugebenDie Regel 2 kann als spezial fall von 3 betrachtet werdenBetonne die Schlüsselrole der Umgebung für die AuswertungHebe die Sonderformen hervor
15Evaluating Combinations The evaluation rule is recursive as one of its steps, the rule needs to invoke itselfEvery element has to be evaluated before the whole evaluation can be doneEvaluating the following combination requires that the evaluation rule be applied to 4 different combinations.( * (+ 2 (* 4 6) ) ( ) )
16Read-Eval-Print-Loop define-rule:Only evaluate the second operandThe name of the first operand is bound to the calculated valueThe overall value of the expression is undefinedprintDifferences betweenScheme versions(define PI 3.14)eval define-rule”PI --> 3.14"Visible worldExecution worldName ValueundefinedPI 3.14
17Read-Eval-Print-Loop printed representation of the valueExpressionExpression2323PI3.14eval name-ruleprintVisible Worldprintcalculate self-ruleExecution World23ValueValueNaming-rule:Look-up the value in the current environment using the name
18Capturing 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 computationKurze Wiederholung der bis hier BesprochenesProzedurdefinition als eine weitaus leistungsfähigere Abstraktionsmittel: Eine zusammengesetzte Operation einen Namen geben mit dem man auf sie sich beziehen kann.
19Creating new procedures We use procedures to capture ways of doing thingssometimes we also use the name functionsimilar to a function in mathematicsThe define special form is used to create new proceduresNameParameter(define (area-of-disk r) (* 3.14 (* r r)))Body of procedure
20Creating 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.5Example - area of a ring: (- (area-of-disk 5) (area-of-disk 3)) = ( ) = 50.24-=
21Creating new procedures Existing procedures can be combined to new, more powerful proceduresExample: calculate area of a ringExample: 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)))
22Informal specifications Typical program specificationUsually not in mathematical terms that can be directly transformed into programsOften rather informal problem specificationsMay contain irrelevant or ambiguous informationExample:“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))
23Errors Your programs will contain errors Possible errors: This is normalDon’t get confused or frustrated by your errorsPossible 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!
24Designing 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 doLater we will refine this recipeAny program development requires at least the following four activities:Understanding the program's purposeThinking about program examplesImplementing the program bodyTesting
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 HalpernUnderstanding the program's purposecalculate 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’…
26Designing Programs Understanding the program's purpose Giving the program a meaningful nameDefinition of a contractWhat kind of information is consumed and produced?Adding the program headerFormulate 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) … )
27Designing Programs Program Examples Help to characterize the input and outputExamples help us to understand the computational process of a program and to discover logical errorsIt is easier to understand something difficult with an exampleFor 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) … )
28Designing Programs Implement the program body Replace the “...” in our header with an expressionIf the input-output relationship is given as a mathematical formula, we just translateIn case of an informally stated formula, we have to understand the computational taskthe 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)))
29Designing Programs 4. Testing i.e. with the DrScheme Testcases (Special -> Insert Testcase)to discover mistakesin 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
31Auxiliary 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 priceAt 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€.
32Auxiliary Functions: Bad Design ;; How NOT to design a program(define (profit price)(- (* (+ 120(* (/ )( price)))price)(+ 180(* .04(+ 120( price)))))))
33Auxiliary 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))))
34Guideline on Auxiliary Functions Formulate auxiliary function definitions for everydependency betweenquantities mentioned in the problem statement orquantities discovered with example calculations.
35Procedures as Black-Box-Abstractions Abstraction helps hiding complexityDetails that are irrelevant for understanding from a special point of view are ignored.
36Procedures 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 ringuser doesn't have to think about the internalsblack-box-abstractionInputOutputWe know what it does, but not how.
37Procedures 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 circleProcedures are written for each of these sub problems.area-of-disk,… primitive procedures …
38Procedures 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.profitrevenuecostattendees
39Procedures as Black-Box abstractions A user defined procedure is called by a name, as are primitive proceduresHow a procedure works remains hidden.area-of-ringarea-of-circlesquareAt 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)))
40constant definition Guideline on Variable Definitions: Better to readEasier to maintainchanges must be made at one point onlyIn 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
41Conditional Expressions Two modes: 1) (if <test> <then-expr> <else-expr>) not optional in Scheme Example: (define (absolute x) (if (< x 0) (- x) x))
42Conditional 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.
43Comments on conditionals A test is „true“ if the evaluation is trueA 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
44Boolean 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
45Boolean 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 falseAn 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
46Boolean functions (boolean=? <expr1> <expr2>) expr1, expr2 evaluated in order of appearance;returns true, if expr1 and expr2 both produce true or both produce falsereturns false, if the operands have different Boolean valuesan error occurs, if an operand evaluates to neither true or false(not <expr>)returns true when <expr> evaluates to falsereturns false when <expr> evaluates to trueFüge Tabellen hier
47Designing Conditional Functions How does our design process change?New Phase: Data analysisWhich different situations exist?Exampleschoose at least one example per situationImplementing the program bodyFirst write down the skeleton of a cond/if expression, then implement the individual casesTestingtests should cover all situationsProgram development requires at least the following four activitiesUnderstanding the program's purposeMaking up examplesImplementing the program bodyTesting
48SymbolsUp to this point, we know numbers and Booleans as primitive valuesOften we want to store symbolic informationnames, words, directionsA 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) errorSymbols are atomic (like numbers, Booleans)Symbols cannot be separated
49Symbols: 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] ))
50Symbols vs. Strings Many of you may know the data type String Symbols are different from StringsSymbols: Are used for symbolic namesatomic,no manipulation,very efficient comparisoncertain restrictions which characters can be representedStrings: Are used for text dataManipulation possible(i.e. search, compose etc.)Comparison is expansiveAny kind of character (string) is possibleStrings are also available in SchemeTo generate with a double quotation mark; compare with string=?For now we will ignore strings
51Reminder: 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).
52Extended Evaluation-Rule Evaluation rule for proceduresThe procedure is a primitive procedureexecute the respective machine instructions.The procedure is a compound procedureEvaluate the procedure bodySubstitute each formal parameter with the respective actual value, that is passed when applying the procedure.(define (f x ) (* x x)) (f 5 )
53Declaring the formal parameters Substitution ModelFictive 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 + b2Declaring the formal parametersDefining the function using formal parametersUsing the general function to solve a particular problemf (3, 2)
54Substitution Model a b ... (define b 2) ... (f 3 2) ... Associating the actual values when executing(define (f a b)(+ (* a a) (* b b)))ab... (define b 2)... (f 3 2) ...... (f b 2) ......a * ab * b+Calling environmentProcedure environment of f
55Substitution 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)))a32b... (define b 2)... (f 3 2) ...... (f b 2) ......a * a3 * 3b * b2 * 2+13Calling environmentProcedure environment of f
56Substitution Model 2 a b 2 ... (define b 2) ... (f 3 2) ... Associating the actual value when executing2ab2... (define b 2)... (f 3 2) ...... (f b 2) ......2 * 2a * ab * b2 * 2+8Calling environmentProcedure environment of f
57Substitution ModelThe purpose of the substitution model is to help us think about procedure applicationIt does not provide a description of how the interpreter really worksTypically, 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 processMore detailed models will follow later onAllows you to “execute” a program on a piece of paper
58Details 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
59Details 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) 7normal order
60Applicative vs. normal order of evaluation Applicative: First evaluate the operator and all operands, then substituteNormal: Evaluate operator, then substitute the (not evaluated) operands for the formal arguments of the operatorImportant, 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 orderWe will see features (assignment, in-/output) which destroy this characteristic laterSometimes both strategies can be very different in the number of evaluation stepsargument is not required normal order winsargument is required several times applicative order wins
61Review: Scheme Things that constitute a Scheme program: Syntax self evaluating 23, true, false,names +, PI, picombinations (+ 2 3) (* pi 4)special forms (define PI 3.14)Syntaxcombination: (oper-expression other-expressions …)special form: a special keyword as first sub routineSemanticscombinations: evaluate subroutines in any order, use the operator for the operands substitution for user-defined proceduresspecial forms: each form has its own
62Summary We have learned: The simplest elements (data/procedures) of SchemeCombination as a composing instrument of simpler elements into more complex elementsHow to make combinations to use them further as elements in other combinationsHow to define own procedures – process pattern – and use them as basic elements of combinations_______________________ Scheme ________________________Separate problems to smaller exact defined tasksProcedures as Black-Box abstractionSemantic of a procedure call as a substitution process