Imperative programming TDDC74 Programming: Abstraction and Modelling z z Repetitionsföreläsning 2 Tilldelning - Imperativ programmering Objektorientering Procedurobjekt Omgivningsdiagram Pekare i cons-celler Anders Haraldsson z Computation as statements that change a program state Imperative programs are a sequence of commands for the computer to perform A functional program evaluates expression. An expression has a value. 2 set! z z Iterative version of factorial set! is used for changing the value bound to a name Syntax: (set! <variable> <value>) Examples: (set! flag #f) (set! x (+ x 1)) (set! fac-value (fac 10)) 3 4 Bank-account example with an object oriented view. Object-oriented programming z Objects – – z z z z 5 (define (factorial n) (let ((res 1)) (define (loop) (if (= n 0) res (begin (set! res (* n res)) (set! n (- n 1)) (loop)))) (loop))) Attributes/properties Behaviour/Methods Class Inheritance Instance Message passing 6 (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) (display balance)) (display “Insufficient funds”))) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m ‘withdraw) withdraw) ((eq? m ‘deposit) deposit) (else (error “Unknown request” m)))) dispatch) 1 Bank-account example z (define my-account (make-account 1000)) z ((my-account ‘withdraw) 100) 900 z ((my-account ‘deposit) 300) 1200 DUGGA 3 Paketering med den objektorienterade modellen. Förstå inkapsling, dispatch-funktionen. Åtkomst av lokala data och procedurer. Förstå kod. Göra tillägg eller ändringar i denna. 7 8 How to Explain What Progams Do z z Definition: Binding In order to explain what programs do, we need to make the states explicit We use a so called environment model of computation 9 z A binding refers to association of a value to a name, for example, x:10, the value of x is 10 f:<procedure>, the value of f is a procedure 10 Definition: Binding and frame z Definition: The Global Environment z A binding refers to association of a value to a name, for example, x:10, the value of x is 10 f:<procedure>, the value of f is a procedure z z z z z A frame is simply a set of bindings The set could be empty Graphical representation: A so called global environment (GE) is distinguished from other environments and contains the global state. GE contains only one frame; this frame is the final frame of all other environemts as well Graphical representation: GE x: 10 y: 20 11 12 2 Lots of Environments Definition: Procedure z GE pi: 3.1415 A procedure is an object that contains two parts: – – E1 x: 42 y: #f a: 33 y: 20 x: 10 y: 20 E4 x: 30 z: 20 a: 10 b: 1729 E5 z one part containing the parameters and the body of the procedure and another part containing the environment in which the procedure was created. Graphical representation: E2 E3 E6 Env w: 127 y: 20 13 Para: Body: 14 The Creation of Environment Diagrams z define Initially, we have z z GE (define <name> <value>) creates a new binding in the current (or first) frame of the current environment CE z define, lambda, set! and procedure application change the diagram 15 16 The Creation of Environment Diagrams z lambda (define y 69) ; in environment GE GE z y: 69 z CE 17 (lambda (par1 par2 ...) body) creates a procedure object in the current environment 18 3 The Creation of Environment Diagrams z set! and evaluating a variable (lambda () (…)) ; in GE GE z z y: 69 CE z Para: Body: 19 (set! <name> <new-value>) changes the old value of <name> in the current environment to <new-value>. The most recent binding in the current environment is affected. To find the value of a variable follows the same strategy. Start to look after the variable in the current environment and follow the frames to find the most recent binding of the variabel 20 The Creation of Environment Diagrams z Procedure Application (set! y 42) ; in GE GE When applying a procedure object to arguments, z create a new environment by creating a new frame in which we bind the parameters to the given arguments z connect this frame to the environment of the procedure and let CE point to this new environment z evaluate the body of the procedure in CE y: 42 CE Para: Body: 21 22 DUGGA 3 Evaluation of let Uppgift 2 z Kunna förklara begreppen och vad som händer i omgivningsdiagrammet. Translate let to its lambda-equivalent and evaluate as usual (define foo (let ((state value)) (lambda (arg) body))) (define foo ((lambda (state) (lambda (arg) body)) value) 23 24 z let*, letrec and others are treated similarly 4 Making Flips Making Flips (define (make-flip) (let ((state 0)) (lambda () (begin (set! state (- 1 state)) state)))) (define (make-flip) (let ((state 0)) (lambda () (begin (set! state (- 1 state)) state)))) är samma som (define (make-flip) ((lambda (state) (lambda () (begin (set! state (- 1 state)) state))) 0)) (define flip (make-flip)) (define blip (make-flip)) (flip) (blip) (flip) 25 26 Environment Diagram: Define function Environment Diagram: create instance > (define (make-flip) ….. ) > (define flip (make-flip)) GE make-flip: GE flip: CE make-flip: CE 27 Para:() Body:((lambda(state) ...) 0) Para:() Body:((lambda(state) (lambda () ...)) 0) Para: (state) Body: (lambda() ...) 28 Environment Diagram: create instance State:0 Para: () Body: (begin ...) Environment Diagram: evaluate instance > (define blip (make-flip)) > (flip) GE make-flip: flip: blip: GE make-flip: CE flip: blip: CE State:0 Para:() Para: (state) Body:((lambda(state) Body: (lambda() ...) ...) 0) 29 Para: () Body: (begin ...) State:0 Para: (state) Body: (lambda() ...) State:1 Para:() Para: (state) Body:((lambda(state) Body: (lambda() ...) ...) 0) Para: () Body: (begin ...) 30 Para: () Body: (begin ...) State:0 Para: (state) Body: (lambda() ...) Para: () Body: (begin ...) 5 DUGGA 3 Evaluate next intance > (blip) Uppgift 3 GE make-flip: flip: blip: Kunna rita omgivningsdiagram där procedurobjekt ingår. CE State:1 Para:() Para: (state) Body:((lambda(state) Body: (lambda() ...) ...) 0) State:1 Para: (state) Body: (lambda() ...) Para: () Body: (begin ...) Para: () Body: (begin ...) 31 32 Mutable (compound) data z z Ändring av car resp cdr-delen i conscellen To modify list structures: Changes the car and cdr pointers (define p ’(a b c)) p e1 a e2 b en () c e2 b en () c (set-car! p ’x) (set-car! cons-cell new-value) (set-cdr! cons-cell new-value) e1 x p p => (x b c) (set-cdr! p (cddr p)) p 33 e1 x en () c e2 b p => (x c) 34 DUGGA 3 Sätta - samman listor – kopiering Uppgift 1 start e1 a ny Kunna rita cons-celler och utföra destruktiva ändringar med set-car! och set-cdr! e2 b slut () e1 x e2 y () (define start ’(a b)) e1 a e2 b (define (append L1 L2) (if (null? L1) (cons (car L1) 36 (define ny (append start slut)) start => (a b) L2 35 (define slut ’(x y)) (append (cdr L1) L2)))) slut => (x y) ny => (a b x y) 6 Sätta - samman listor – pekarändring Mutable lists – difficult to see consequences start z e1 a (define x ‘(a b c)) (define y ‘(d e)) z (set-car! x y) z (set-cdr! y ‘f) z (define z (cons (cdr x) (cdr x))) z z -> ? z = ((b c) b c) e2 b z ny slut e1 x e2 y () (define start ’(a b)) (define slut ’(x y)) (define (append! L1 L2) (if (null? L1) start => (a b x y) L2 (begin (set-cdr! (last L1) L2) 37 (define ny (append! start slut)) L1))) slut => (x y) ny => (a b x y) 38 Identity and sharing z z z Number of cons-cells eq? cannot be applied to lists (to see if two lists are identicel by contents), however eq? can test if x and y are the same object (equal pointers) (list ’a ’b) = (cons ’a (cons ’b ’())) (define p (let ((cons-cell (cons ’a ’()))) (cons cons-cell (cons cons-cell ’())))) p => ((a) (a)) equal? checks if two lists have the same elements e1 e1 a 39 40 Queue primitives z z z z z z 41 () e2 () a () (eq? (car p) (car (cdr p))) = ? e1 e2 e1 a () () (eq? (car p) (car (cdr p))) = ? Queue make-queue: -> queue empty-queue?: queue -> bool front-queue: queue -> item insert-queue!: item x queue -> queue delete-queue!: queue -> queue print-queue: queue -> 42 (define bank-queue (make-queue)) (insert-queue! ’kalle bank-queue) (insert-queue! ’stina bank-queue) (front-queue bank-queue) => kalle (delete-queue! bank-queue) (insert-queue! ’lisa bank-queue) (insert-queue! ’eva bank-queue) (front-queue bank-queue) => stina (delete-queue! bank-queue) (print-queue bank-queue) lisa eva 7 Creating an Abstract datatype (ADT) z z z z z z Queue representation Constructors Selectors Mutators (!-procedures) Recognizors Printers z To allow fast access we need two pointers – – The front of the queue, i.e. the first pair The rear of the queue, i.e. the last pair Now that we have introduced set!, set-car!, and setcdr!, the picture is complete. e1 a eb 2 Front of queue 43 c () Rear of queue 44 Queue representation z z Queue implementation Empty queue e()1 (define (insert-queue! Item queue) (let ((new-pair (cons item '()))) (cond ((empty-queue? queue) (set-car! queue new-pair) (set-cdr! queue new-pair) queue) (else (set-cdr! (cdr queue) new-pair) (set-cdr! queue new-pair) queue)))) () One element queue e1 e1 a () 45 46 DUGGA 3 Queue with object oriented packaging Uppgift 4 (define (make-queue) (let ((queue (cons ‘() ‘())) (define (empty?) (null? (car queue))) (define (front) (car (car queue))) … … (define (dispatch m) (cond ((eq? m ‘empty) empty?) ((eq? m ‘insert) (lambda (item) (insert! item))) ((eq? m ‘front) front) ((eq? m ‘delete) delete!) ((eq? m ‘print) print) (else (error “Unknown request” m)))) dispatch) Skapa andra datastrukturer (än sekventiella listor) där man får en effektivare representation om man ändrar pekare. En kö. Konstant tid att hitta början resp slutet av kön. Implementeras lämpligen som en abstrakt datatyp (ADT). 47 Queue-head e1 48 8