public
Last active

  • Download Gist
bank-account-class.md
Markdown

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.