Create a gist now

Instantly share code, notes, and snippets.

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

Deposit money:

> (b0.deposit 100)

Verify the deposit:

> b0.balance

Withdraw money:

> (b0.withdraw 50)

Look at the new balance:

> b0.balance

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

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