1 / 61

Introduction to Computer Science I Topic 1: Basic Elements of Programming

Introduction to Computer Science I Topic 1: Basic Elements of Programming. Prof. Dr. Max Mühlhäuser Dr. Guido Rößling. What is Programming?. Let us take a look at what some godfathers of programming have to say:. „To program is to understand“ Kristen Nygaard.

lionel
Download Presentation

Introduction to Computer Science I Topic 1: Basic Elements of Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer Science ITopic 1: Basic Elements ofProgramming Prof. Dr. Max MühlhäuserDr. 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 denote23 → 23-36 → -36 • Booleanvalues • trueandfalse • Also selfevaluating • Names forbuilt-in procedures • Examples: +, *, /, -, =, … • What is the value of such an expression? • The value of +isa 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. Language Elements - Compound Elements left parenthesis rightparenthesis • (+ 2 3) 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.

  8. represents the application of the procedure to the numbers Language Elements - Compound Elements • Compound Elements: • 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 left parenthesis rightparenthesis • (+ 2 3) Operator Operands

  9. Language Elements - Compound Elements • 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. Language Elements - Abstractions • Create a complex thing by combining more primitive things, • name it, • treat it like a primitive. • Simplestmeansofabstraction: define (define score (+ 23 7)) (define PI 3.14)

  11. Language Elements - Abstractions • 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 valueexample: (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 an 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 (+ 30 15)) (* 100 (/ score total)) • Note: we already did this implictly (looking up a name in an environment) for +, *, … + * / … 30 score 45 total

  14. Evaluation Rules • Self evaluating (self-rule) 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 (name-rule) 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))

  15. Evaluation Rules • Theevaluation ruleis 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) ) (+ 3 5 7) )

  16. Differences between Scheme versions print evaldefine-rule 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 (define PI 3.14) ”PI --> 3.14" Visible world Name Value Execution world undefined PI 3.14

  17. PI 3.14 print evalname-rule 3.14 Read-Eval-Print-Loop printed representation of the value Expression Expression 23 23 Visible World print calculateself-rule Execution World 23 Value Value Naming-rule: Look-up the value in the currentenvironment using the name

  18. Capturing common patterns • Here are some common patterns(* 3.14 (* 5 5)) (* 3.14 (* 23.2 23.2)) (* 3.14 (* x x)) • How do we generalize • i.e. how to express the idea of “circle area computation”? They are instances of a circle area computation

  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 definespecial form is used to create new procedures Name Parameter (define (area-of-disk r) (* 3.14 (* r r))) Body ofprocedure

  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))  = (78.5 - 28.26) = 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 itsemployees $12 per hour. A typicalemployeeworksbetween 20 and 65 hours per week. Develop a programthatdeterminesthe wage of an employeefromthenumberofhoursofwork.” problem analysis (define (wage hours) (* 12 hours))

  23. Errors • Your programs will contain errors • This is normal • Don’t get confused or frustrated by your errors • Possible errors: • Wrong number of brackets, e.g. (* 3 (5) • The operator of a procedure call is not a procedure, e.g. (10) (10 + 20) • Wrong type , other typical runtime errors, e.g.: (+ 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. Designing Programs • 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’ • … “If you can't write it down in English, you can't code it.“ Peter Halpern

  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 Example: ;; 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. Design von Programmen • 4. Testing: UsethefunctionsofScheme! • (check-expectactualexpected) • Comparesthe „actual“ valuewiththe „expected“ value • Problematicforfloatingpointnumberssincetheresultis not exact (markedby a preceeding „#i“ forthevalue) • Example: (check-expect (* 2 2) 4) • (check-withintestexpecteddelta) • Checks ifthevaluetotest (floatingpointnumber in mostcases) iscorrectwithin a rangeofdelta, e.g. delta = 0.0001. • Example: (check-within (area-of-ring 5 2) 65.9 0.5) • (check-errortestmessage) • Checks ifthefunctioncallraisestheexpectederrormessage • Errors in a functionfunccanberaisedby (error 'function "message") • Tests having a failureareshown in a separate window

  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 (* (/ 15 .10) (- 5.00 price))) price) (+ 180 (* .04 (+ 120 (* (/ 15 .10) (- 5.00 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 (* .04 (attendees ticket-price)))) (define (attendees ticket-price) (+ 120 (* (/ 15 .10) (- 5.00 ticket-price))))

  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 are ignored(depends on the point of view)

  36. Procedures as Black-Box abstractions • Will consider several fundamental kinds of abstraction in this course. • A Procedural abstraction is one of: • area-of-ring computes the area of a ring • The user doesn't have to think about the internals black-box-abstraction Output Input 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. profit cost revenue attendees 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 abstractionfor revenue/cost.

  39. area-of-ring area-of-circle square Procedures as Black-Box abstractions • A user defined procedure is called by a name, as are primitive procedures • How a procedure works remains hidden. 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 3.14159) 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)]))

  43. 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 theexpressions 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

  44. 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 arefalse • An error occurs if a value evaluates to neither true or false

  45. Boolean functions (boolean=? <expr1> <expr2>) • expr1, expr2evaluated 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 if <expr> evaluates to false • returns false if <expr> evaluates to true

  46. 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 theskeletonof a cond/ifexpression, 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

  47. 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 (e.g. 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

  48. 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] ))

  49. 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

  50. Reminder: The Evaluation-Rule • 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). Up to now we have only considered built-in procedures. How to evaluate procedures that are defined by the programmer?

More Related