Skip to content

Instantly share code, notes, and snippets.

@dharmatech
Created April 7, 2010 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharmatech/358639 to your computer and use it in GitHub Desktop.
Save dharmatech/358639 to your computer and use it in GitHub Desktop.

A simple bank account class:

(class bank-account

  ((mutable balance))

  ((deposit amount)
   (balance! (+ balance amount)))

  ((withdraw amount)
   (when (> amount balance)
     (error #t "Account overdrawn"))
   (balance! (- balance amount))))

The class has a single mutable field balance and two methods, deposit and withdraw.

Make a new bank-account:

> (define b0 (make-bank-account 0))

Declare that the variable is a bank-account:

> (is-bank-account b0)

Look at the balance:

> b0.balance
0

Deposit money:

> (b0.deposit 100)

Verify the deposit:

> b0.balance
100

Withdraw money:

> (b0.withdraw 50)

Look at the new balance:

> b0.balance
50

Ask for more than is in the account:

> (b0.withdraw 500)
Unhandled exception
 Condition components:
   1. &error
   2. &who: #t
   3. &message: "Account overdrawn"
   4. &irritants: ()

The methods are available as procedures bank-account::deposit and bank-account::withdraw. Example:

> (bank-account::deposit b0 100)

Verity the deposit:

> b0.balance
150

This wacky experiment is available in the (dharmalab records class) library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment