logoalt Hacker News

so-cal-schemer • yesterday at 10:17 PM • 1 reply • view on HN

Uses an internal lambda for dispatching on messages.

We can also create objects that handle deposits as well as withdrawals, and thus we can represent simple bank accounts. Here is a procedure that returns a “bank-account object” with a specified initial balance:

  (define (make-account balance)
    (define (withdraw amount)
      (if (>= balance amount)
          (begin (set! balance 
                       (- balance amount))
                 balance)
          "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: 
                   MAKE-ACCOUNT" m))))
    dispatch)
Each call to make-account sets up an environment with a local state variable balance. Within this environment, make-account defines procedures deposit and withdraw that access balance and an additional procedure dispatch that takes a “message” as input and returns one of the two local procedures. The dispatch procedure itself is returned as the value that represents the bank-account object. This is precisely the message-passing style of programming that we saw in 2.4.3, although here we are using it in conjunction with the ability to modify local variables.

3.1.1 Local State Variables

https://sarabander.github.io/sicp/html/3_002e1.xhtml#g_t3_00...


Replies

Jtsummers • yesterday at 10:27 PM

A closure, specifically, because closures are a poor man's object.

https://wiki.c2.com/?ClosuresAndObjectsAreEquivalent

➕ show 1 reply