Last active
October 13, 2015 08:22
-
-
Save abuseofnotation/304ffd77afc02107581c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;Stolen from "Structure and Interpretation of Computer Programs" | |
| ;https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-20.html#%_sec_3.1.1 | |
| ;Implementation: | |
| ;--------------- | |
| (define (make-account balance) | |
| ;withdraw method: | |
| (define (withdraw amount) | |
| (if (>= balance amount) | |
| (begin (set! balance (- balance amount)) | |
| balance) | |
| "Insufficient funds")) | |
| ;deposit method: | |
| (define (deposit amount) | |
| (set! balance (+ balance amount)) | |
| balance) | |
| ;method dispatcher | |
| (define (dispatch m) | |
| (cond ((eq? m 'withdraw) withdraw) | |
| ((eq? m 'deposit) deposit) | |
| (else (error "Unknown request -- MAKE-ACCOUNT" | |
| m)))) | |
| dispatch) | |
| ;Usage: | |
| ;--------------- | |
| (define acc (make-account 100)) | |
| ((acc 'withdraw) 50) | |
| ; -> 50 | |
| ((acc 'withdraw) 60) | |
| "Insufficient funds" | |
| ((acc 'deposit) 40) | |
| ; -> 90 | |
| ((acc 'withdraw) 60) | |
| ; -> 30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment