Last active
August 29, 2015 14:20
-
-
Save beoliver/a3f730e895db521104cd to your computer and use it in GitHub Desktop.
Scheme closure balance example
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
| (define (make-balance) | |
| (let ((balance 0)) | |
| (define add-method | |
| (lambda (value) (set! balance (+ balance value)))) | |
| (define get-method | |
| (lambda () balance)) | |
| (define sub-method | |
| (lambda (value) | |
| (if (<= value balance) | |
| (set! balance (- balance value)) | |
| (begin | |
| (display "INSUFFICIENT FUNDS") | |
| (newline))))) | |
| (lambda (arg . rest) | |
| (cond ((equal? arg "get") (get-method)) | |
| ((equal? arg "add") (add-method (car rest))) | |
| ((equal? arg "sub") (sub-method (car rest))) | |
| (#t (begin (display "UNKNOWN COMMAND") (newline))))))) | |
| ;; in the REPL... | |
| > (define balance (make-balance)) | |
| > (balance "get") | |
| 0 | |
| > (balance "add" 10) | |
| > (balance "get") | |
| 10 | |
| > (balance "add" 1) | |
| > (balance "get") | |
| 11 | |
| > (balance "sub" 20) | |
| INSUFFICIENT FUNDS | |
| > (balance "whagdakjdadsl" 92) | |
| UNKNOWN COMMAND | |
| > (balance "dlakjdkaljd") | |
| UNKNOWN COMMAND | |
| > (balance "sub" 6) | |
| > (balance "get") | |
| 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment