The Science of Programming/SwayPresentations/Objects/ClosuresAsObjects

Closures as Objects

From Structure and Interpretation of Computer Programs:

   (define (account amount)
       (define (deposit d) (set! amount (+ amount d)))
       (define (withdraw w) (set! amount (- amount w)))
       (lambda (msg arg)
           (cond
               ((eq msg 'withdraw) (withdraw arg))
               ((eq msg 'deposit) (deposit arg))
               (else (error "unknown message: " msg))
               )
           )
       )

Now we can treat account as a constructor:

   (define a (account 100))
   (a'withdraw 10)
   (a'deposit 20)

The closure that translates messages to function calls is a hack.


Next Previous Top