The Science of Programming/SwayPresentations/Objects/EnvironmentsAsObjects

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Environments as Objects

If you are going to use an existing 'object' as an 'Object', then environments are a better choice.

In Scheme, environments are first-class 'objects'.

  (define (account amount)
      (define (deposit d) (set! amount (+ amount d)))
      (define (withdraw w) (set! amount (- amount w)))
      (procedure-environment (lambda () 1))
      )

We need the 'dot' operator:

   (define (dot obj message)
       (eval message obj)
       )

Now, our account looks like:

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

Next Previous Top