; To understand this, study my lecture notes and read the handout ; "modularity, objects and state". The examples here follow the handout ; closely. ; How to do OOP in Scheme? ; need to extend pure lambda calculus with state info. (define x 10) (define x 11) ; redefines x (set! x (+ x 1)) ; doesn't redefine, but CHANGES value of old x, i.e, x++; ; scheme function that returns a different value each time: (define counter (let ((x 0)) (lambda () (begin (set! x (+ 1 x)) (- x 1))))) ; Note that the lambda is created inside a local scope (environment) with ; a binding for x. ; The value returned is a function "closure" that contains an enviornment. ; The lambda term is now "stateful" - its effect is persistent after ; the function call. ; suppose I did (define counter2 (lambda () (let ((x 0)) (begin (set! x (+ 1 x)) x)))) ; Then this is really a C function: ;int counter() ;{ ; int x = 0; ; x = x+1; ; return x; ;} ; But the other function you can't write in C ; WHAT HAVE WE GOT HERE? WE'VE GOT OBJECTS!!!!!! (define (makeaccount balance) (define (withdraw a) (begin (set! balance (- balance a)))) (define (deposit a) (begin (set! balance (+ balance a)))) (define (inquiry) balance) (define (chargefee) (set! balance (- balance 2))) ; "private" function (lambda (method) (cond ((equal? method 'withdraw) withdraw) ((equal? method 'deposit) deposit) ((equal? method 'inquiry) (inquiry)) (#t "no such method")))) (define myaccount (makeaccount 100)) (define youraccount (makeaccount 200)) ((myaccount 'withdraw) 30) ((youraccount 'deposit) 50) (myaccount 'inquiry) (youraccount 'inquiry)