TDDC74 Programming: Abstraction and Modelling SICP 1 – Lecture 1-3 Anders Haraldsson z Dessa bilder har tagits fram av Annika Silvervarg, som var föreläsare vt 2007. z Kursen ges i år på svenska. z Mycket av materialet är på engelska, eftersom kursen tidigare flera gånger givits helt på engelska. I år kan materialet därför ha en blandning av svenskt och engelskt material. 2 1 Kursens personal z z z z z z z 3 z Kursens bakgrund Anders Haraldsson, examinator, föreläsningar, lektioner Pierre Östlund, lektioner, laborationer klass Y1a Emil Nielsen, lektioner, laborationer klass Y1b Anders Haraldsson, lektioner, laborationer klass Y1c Johan Jernlås, lektioner, laborationer klass Yi1,MAT2 Sebastian Abrahamsson, laborationer Y1c, handledning alla laborationer Jalal Maleki, studierektor Marie Ekström Lorentzon, kurssekreterare z z z 5 z Utvecklad på MIT z Fokus på abstraktion och modellering Lisp-dialekten Scheme är ett “gammalt” språk väl valt för detta syfte – z z Ges för alla ingenjörer och datavetare Liknande kurs (men i Lisp-dialekten Common Lisp) ges för Datateknik (D) och Datavetenskapliga (C) programmen; TDDC67 Funktionell programmering och Lisp 4 Kursens syfte z z Kursens innehåll Kursens syfte är att studenterna ska utveckla förmåga att representera och lösa problem med hjälp av konstruktioner i datorspråk. Efter avslutad kurs ska studenterna kunna: z SICP1 z SICP2 redogöra för grundläggande datavetenskapliga begrepp relaterade till programmering och programspråk, särskilt funktionella språk metodiskt lösa programmeringsrelaterade problem i en interaktiv programutvecklingsmiljö representera problem och lösningar till dessa i form av rekursiva och iterativa algoritmer och kunna uppskatta tid- och rymdkomplexiteten för enklare fall konstruera abstraktioner som möjliggör design av program som är lättförståliga, återanvändbara och kan underhållas lättare genomföra ett mindre programmeringsprojekt z SICP3 – – – Abstraktioner baserat på procedurer Abstraktioner baserat på data Abstraktioner baserat på objekt 6 1 Kursens organisation z z z z z Kursens examination Föreläsningar Lektioner Laborationer Projekt Duggor / Tentamen 7 z z z TEN1 Skriftlig tentamen / duggor (U,3,4,5) 2 hp LAB1 Laborationer (U, G) 3 hp PRA1 Projekt (U,3,4,5) 3 hp Slutbetyget på kursen baseras på i först hand på betyget på duggorna / tentamen. Slutbetyget kan höjas ett steg om z man klarat de ordinarie duggorna under VT1 z betyget på projektet är minst ett steg högre än betyget på duggorna z att laborationsserien och projektet är redovisade i tid. 8 Kursbok Programming z z Boken kallas SICP. z De tre första kapitlen ingår i denna kurs. z z Computational processes (beräkningsprocesser) … manipulate data … are controlled by rules, i.e. a program/procedure … written in a specific programming language … in this course Scheme Kursboken finns även på nätet under http://mitpress.mit.edu/sicp/ 9 10 Elements Of Programming z z z Expressions Primitive expressions Means of combination Means of abstraction z Primitive – z Compound (sammansatt uttryck) – – z z Form – syntax Meaning - semantics – – – 11 eg. numbers: 1, 3.14 eg. application of mathematical primitive procedure on numbers: (+ 1 3.14) (operator operand … operand) Can be nested: (+ (* 2 3) (- 4 5)) Operator first -> prefix notation (In mathematics wirh operator between operandes -> infix notation) 12 2 Constants (konstanter) Primitive Expressions z z Constants Names z z z z z 13 truth-value: #t, #f (sanningsvärde) integer: 42, +1789, -2 (heltal) rational: 3/4, -22/7 (bråk) floating: 3.1415, -10e10, 2e-3 (flyttal) complex: 3.1+4i, 2-3i (komplext tal) 14 Names (identifierare) z Read-Eval-Print z A name is a sequence of characters that does not constitute a number or other syntactic object in Scheme: z z + square week23 i-am-a-name-in-scheme-too +inf.0 http://www.google.com/ -1+ 2+2 15 z z z z z 16 Evaluating Numbers z z z Read an expression Evaluate it according to given rules Print the result (+ 2 (* 3 4)) > 14 (define pi 3.14) (+ 2 pi) > 5.14 (define (n-pi n) (* n pi)) (n-pi 4) > 12.56 Evaluating Truth Values (sanningsvärden) Read the number Evaluate (beräkna) it Print the value z z z #t and #f are the truth values in Scheme #t represents the value ’true’ (sant) #f represents the value ’false’ (falskt) 4 is read and we get ’4’ and it is evaluated to the number 4 17 18 3 Compound Expressions z z z Compound Expressions Procedure Application Special Forms Abstraction Operators z z z z 19 20 Functions In Mathematics z z z Example Function What element in R (Range) corresponds to an element in D (Domain) R and D are both sets The function mapping D to R is also a set – a set of pairs chosen from D and R 21 z Domain: {..., -2, -1, 0, 1, 2, ...} Range: {..., -2, -1, 0, 1, 2, ...} Function: {..., < -2, 4 >, < -1, 1 >, < 0, 0 >, < 1, 1 >,...} z f(x) = x2 z z 22 Functions In Programs z z 23 Primitive Function Application (<function> <arg1> <arg2> ...) User-Defined Function Application (<function> <arg1> <arg2> ...) Special Forms: (if <condition> <then> <else>) (and <exp1> <exp2> ...) (or <exp1> <exp2> ...) Abstraction: (define <name> <value>) (lambda <args> <body>) grouping together many procedures (lambda (n) (* n n)) How to map elements of D to R? Use algorithms or descriptions that do the mapping z Example: (lambda (n) (* n n)) that given n computes n*n z λx . x2 eller λn . n2 z Example: (lambda (r) (* 2 (* 3.1415 r))) z z Parameter (formell parameter): n Body (funktionskropp): (* n n) 24 4 ((lambda (n) (* n n)) 7) z z z z Parentheses Parameter (formell parameter): n Body: (* n n) Argument (aktuell parameter, argument): 7 Value: 49 25 Parentheses are for helping us to understand the structure of our programs, not for confusing us z ((lambda (n) (* n n)) 7) z At the same time we must admit they (in the beginning) are a pain ... but we have no choice 26 Special forms z – z IF Tests – if cond z (if <condition> <then> <else>) z (lambda (amount) (if (< amount 10000) 0 1.5)) z ((lambda (amount) (if (< amount 10000) 0 1.5))) 50000) > 1.5 Logical operators – – – and or not 27 28 COND z z 29 z Logical Operators Examples (cond (predicate-1 consequence-1) (predicate-2 consequence-2) ... (predicate-n consequence-n)) z (lambda (amount) (cond ((< amount 0) 0) ((< amount 10000) 0.5) ((< amount 50000) 1.1) ((>= amount 50000) 1.5))) z The last case can be described as (else 1.5) ; in all other cases z z z z (and <e1>,…, <en>) (or <e1>,…, <en>) (not <e1>) (and (> x 2) (< x 6)) (or (> x 2) (< x -2)) (not (< x 3)) 30 5 Combining Logical Operators Vanlig fallgrop z (or (and (> x 2) (< x 6)) (and (> x -6) (< x -2))) z (if (odd? x) #t #f) kan lika gärna skrivas (odd? x) z (not (odd? x)) z (if (odd? x) #f #t) kan lika gärna skrivas (not (odd? x)) 31 32 What Is Abstraction? z z z z Abstraction In Programming Ignoring details Packaging details Concentrating on the whole rather its parts z z Naming towards application (real objects) than representation (computers objects) 33 34 Abstraction In Scheme z Abstraction Operators (define pi 3.1415) z z 35 Giving a name to 3.1415 is abstraction Giving a name to (lambda (n) (* n n)) is abstraction z (define square (lambda (n) (* n n))) z (define circle-area (lambda (r) (* pi (square r)))) z define lambda Block-structures: grouping procedures 36 6 define z z z lambda-expression Is used to give names to values and procedures For the time being, let’s just imagine that define puts names and their values in some sort of table. In chapter 3 of the book more detail is revealed 37 z z (lambda <args> <body>) Creates a function object with the given arguments and body 38 Shorthand/Syntactic sugar z z Evaluating Function Application Naming and defining procedures can be done in one step z z (define area (lambda (r) (* pi (square r)))) Substitution model: Given a procedure call of the form: (<function> <arg1> <arg2> ...) – – – z (define (area r) (* pi (square r))) z 39 This is according to the applicative method 40 Evaluating the Special Forms: if 41 Evaluate the function to get the procedure body Evaluate the arguments Replace occurrences of the parameters with value of the corresponding arguments in the body of <function> and evaluate the resulting expression z (if <condition> <then> <else>) z Evaluate <condition>, if true then evaluate <then> otherwise evaluate <else> Evaluating the Special Forms: cond z (cond (predicate-1 consequence-1) (predicate-2 consequence-2) ... (predicate-n consequence-n)) z Evaluate predicate-i, if true, evaluate consequence-i and return its value as the value of the whole CONDexpression 42 7 Evaluating the Special Forms: and Evaluating the Special Forms: or z (and <arg-1> <arg-2> ...) z (or <arg-1> <arg-2> ...) z Evaluate arguments from left to right until a #f value reached in which case return #f, return #t otherwise z Evaluate arguments from left to right until a #t value reached in which case return #t, return #f otherwise 43 44 Repetition IF and COND z Def1 av absolutbelopp: – – – z Cond, cond -> if (cond ((> x 0) x) ((= x 0) 0) ((< x 0) (- x))) z (if (> x 0) x (if (= x 0) 0 (- x))) Def2 av absolutbelopp: – – x om x>=0 -x om x<0 45 46 If, if -> cond 47 z x om x>0 0 om X=0 -x om x<0 z (if (>= x 0) x (- x)) z (cond ((>= x 0) x) (else (- x))) Distance function z Define a function that takes two coordinates (i.e. 4 numbers) as argument and calculate the distance between them. 48 8 Distance function z Substitution model (define distance (lambda (x1 y1 x2 y2) (sqrt (+ (square (- x2 x1)) (square (- y2 y1)))))) z z z z z (define square (lambda (n) (* n n))) z z z 49 (distance 0 0 3 4) (sqrt (+ (square (- 3 0)) (square (- 4 0)))) (sqrt (+ (square 3) (square 4))))) (sqrt (+ (* 3 3) (* 4 4))) (sqrt (+ 9 16)) (sqrt 25) 5 50 Procedures and Processes z Procedures and Processes When a procedure is evaluated or executed, it creates a process 51 z z Recursive Processes Iterative Processes 52 Recursion z z z z 0! = 1, N! = N * (N-1)! Defining the meaning of a function in terms of itself Nothing strange about this n! = n * (n-1)! when n > 0 0! = 1 (define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))) Short hand syntax: (define (fact n) (if (= n 0) 1 (* n (fact (- n 1)))))) 53 54 9 Substituion Model Substituion Model Use substitution model to find (fact 4): (fact 4) (* 4 (fact 3)) (* 4 (* 3 (fact 2))) (* 4 (* 3 (* 2 (fact 1)))) (* 4 (* 3 (* 2 (* 1 (fact 0))))) at this stage expansion is complete (* 4 (* 3 (* 2 (* 1 1)))) (* 4 (* 3 (* 2 1))) (* 4 (* 3 2)) (* 4 6) 24 z z z z z z 55 56 trace.ss z z Linear Recursive Process Characteristics (require (lib "trace.ss")) (trace fact) z z z z 57 A recursive call to the procedure Each recursive creates a delayed computation Time complexity grows linearly with respect to the size of the input parameter O(n) Space complexity grows linearly with respect to the size of the input parameter O(n) 58 Iterative Factorial z (define (fact n) (fact-iter n 1) z (define (fact-iter n prod) (if (= n 0) prod (fact-iter (- n 1) (* n prod)))) Substitution model The extra parameter is often called the result parameter. 59 (fact 4) evaluate 4 to get its value (which happens to be 4) in the body of fact, replace n with this value to get: (if (= 4 0) 0 (* 4 (fact (- 4 1)))) since (= 4 0) is evaluated to false, we evaluate (* 4 (fact (- 4 1))) in order to evaluate this we evaluate the arguments of * which are 4 and (fact (- 4 1)) 4 is evaluated to 4 and (fact (- 4 1)) is separately evaluated in a similar fashion to the evaluation of (fact 4) 60 (fact 4) (fact-iter 4 1) (fact-iter (- 4 1) (* 4 1)) (fact-iter 3 4) (fact-iter (- 3 1) (* 3 4)) (fact-iter 2 12) (fact-iter (- 2 1) (* 2 12)) (fact-iter 1 24) (fact-iter (- 1 1) (* 1 24)) (fact-iter 0 24) 24 10 Iterative Process Characteristics z z z z Fibonacci Numbers A recursive call The recursive call does not create delayed computation Time complexity is linear with respect to the size input parameter O(n) Space complexity is constant (independent of the size of input) O(k) 61 0, 1, 1, 2, 3, 5, 8, 13, ... 62 Recursive Fibonacci z Tree Recursive Process (define fib (lambda (n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2))))))) 63 (fib 5) (+ (fib 4) (fib 3)) (+ (+ (fib 3) (fib 2)) (fib 3)) (+ (+ (+ (fib 2) (fib 1))(fib 2)) (fib 3)) (+ (+ (+ (+ (fib 1) (fib 0))(fib 1))...)...) 64 Tree Recursive Processes z z z z 65 Iterative Fibonacci Multiple recursive calls in the same expression Recursive call creates delayed computation Time complexity grows exponentially O(kn) Space complecity is linear O(n) z (define fiter (lambda (n f0 f1 count) (if (= count n) f1 (fiter n f1 (+ f0 f1) (+ count 1))))) 66 11 Newtons metod för approximering av kavdratrötter z z z z Newtons metod för approximering av kavdratrötter Gör en intital gissning (valigtvis 1) Dela det sökta talet med gissningen Ta medelvärdet av gissningen och kvoten för att få en ny gissning Upprepa de två sista stegen 67 z (define sqrt (lambda (n) (sqrt-help 1 n))) z (define sqrt-help (lambda (guess n) (if (good-enough? guess n) guess (sqrt-help (improve guess n) n)))) 68 Newtons metod för approximering av kavdratrötter Newtons metod för approximering av kavdratrötter z (define good-enough? (lambda (guess n) (< (abs (- (square guess) n)) 0.001))) z (define improve (lambda (guess n) (average guess (/ n guess)))) z (define abs (lambda (n) (if (< n 0) (- n) n))) z (define average (lambda (x y) (/ (+ x y ) 2))) 69 70 Procedures Without Arguments z (define random-number (lambda () (random 10))) z (random-number) >6 Scope z (define add10 (lambda (number) (+ number 10))) z The scope of ’number’ is the body of this procedure and it can only be used there z (add10 3) > 13 number >ERROR z 71 72 12 Scope: Local or Global Shadowing z (define number 23) z (define number 23) z (define add10 (lambda (number) (+ number 10))) z (define add10 (lambda (number) (+ number 10))) z (add10 10) > 20 (add10 number) > 33 z Add10 shadows the global value of number inside its body z 73 74 Higher-Order Procedures z z Various Sums Procedures as arguments Procedures as returned values 75 (define (sum-ints a b) (if (> a b) 0 (+ a (sum-ints (+ a 1) b)))) z (define (sum-squares a b) (if (> a b) 0 (+ (square a) (sum-squares (+ a 1) b)))) z (define (sum-cubes a b) (if (> a b) 0 (+ (cube a) (sum-cubes (+ a 1) b)))) 76 Similarities 77 z z (define (sum-ints a b) (if (> a b) 0 (+ a (sum-ints (+ a 1) b)))) z (define (sum-squares a b) (if (> a b) 0 (+ (square a) (sum-squares (+ a 1) b)))) z (define (sum-cubes a b) (if (> a b) 0 (+ (cube a) (sum-cubes (+ a 1) b)))) General Sum z (define (sum a b term) (if (> a b) 0 (+ (term a) (sum (+ a 1) b term)))) 78 13 General Sum sum-ints z (define (sum-squares a b) (sum a b square)) z (define (sum-cubes a b) (sum a b cube)) Introduce a local function: How to write sum-ints? z z 79 z (define (sum-ints a b) (define (identity x) x) (sum a b identity)) 80 Two Kinds of Accumulation z (define (sum a b term next) (if (> a b) 0 (+ (term a) (sum (next a) b term next)))) z (define (mult a b term next) (if (> a b) 1 (* (term a) (mult (next a) b term next)))) 81 Similarities z (define (sum a b term next) (if (> a b) 0 (+ (term a) (sum (next a) b term next)))) z (define (mult a b term next) (if (> a b) 1 (* (term a) (mult (next a) b term next)))) 82 Accumulation in General z 83 (define (sum-ints a b) (sum a b (lambda (x) x))) Accumulation in General (define (acc a b term next init op) (if (> a b) init (op (term a) (acc (next a) b term next init op)))) z (define (acc a b term next init op) (if (> a b) init (op (term a) (acc (next a) b term next init op)))) z (define (sum a b term next) (acc a b term next 0 +)))) 84 14 Procedures as returned values z z compose The composition of two functions f and g is defined as f(g(x)) Define a procedure compose that implements composition z (define (compose f g) (lambda (x) (f (g x)))) z (define test-newton (compose square sqrt)) (define test-newton (lambda (x) (square (sqrt x)))) z (test-newton 1) > 1.0 (test-newton 2) > 2.0000060073048824 z 85 86 make-greeter z (define (make-greeter name) (lambda () (display “Hello ”) (display name))) z (define greet (make-greeter “Annika”)) (define greet (lambda () (display “Hello ”) (display “Annika”))) z (greet) Hello Annika > LET, LET* z z 87 z z z 88 LET example z 89 LET and LET* are a kind of alternative syntactic forms for constructing local variables in procedures (let ((<var1> <exp1>) (<var2> <exp2>) … (<varn> <expn>)) body) Facilitate understandning of programs Can be used to avoid repeated computations Let binds it variables in parallell, use let* for sequential LET example (define fiter (lambda (n f0 f1 count) (let ((new-f0 f1) (new-f1 (+ f0 f1))) (if (= count n) f1 (fiter n new-f0 new-f1 (+ count 1)))))) z (define (sum-and-test x y test-fn) (let ((sum (+ x y))) (if (test-fn sum) sum (display “The sum did not pass the test”)))) 90 15 91 LET example, alternatives Where Do Algorithms Come From (define (sum-and-test x y test-fn) ((lambda (sum) (if (test-fn sum) sum (display “The sum did not pass the test”))) (+ x y))) z (define (sum-and-test x y test-fn) (define (helper sum) (if (test-fn sum) sum (display “The sum did not pass the test”))) (helper (+ x y))) z z 92 Example Errors Equation: C/100=(F - 32)/180 can be formulated as two algorithms that compute C or F z z (define c (lambda (f) (* 100 (/ (- f 32) 180)))) z z (define f (lambda (c) (+ (/ (* c 180) 100) 32))) z 93 z Syntactic Error Expression impossible to evaluate Semantic Error Meaningless expressions Algorithmic Error Solving the wrong problem 94 Summary z Summary Expressions z Primitive z – z z – Constants Names Evaluation and substitution model Procedures and processes – z z Function applications Special forms z If – Cond – Logical operators: and, or, not – z – Scope: local and global variables z Higher order functions – Lambda Define Recursive processes Iterative processes Tree-recursive processes z – Abstraction – Recursive procedures z Compound z 95 Thinking and Problem Solving Fortunately many problems are solved already. ”Just” translate the solutions to algorithms Many mathematical formulas can easily be translated to algorithmic descriptions – Let Functions as arguments Functions as returned values 96 16