Skip to content

Instantly share code, notes, and snippets.

@abuseofnotation
Last active October 13, 2015 08:22
Show Gist options
  • Select an option

  • Save abuseofnotation/304ffd77afc02107581c to your computer and use it in GitHub Desktop.

Select an option

Save abuseofnotation/304ffd77afc02107581c to your computer and use it in GitHub Desktop.
;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