Created
May 4, 2010 05:52
-
-
Save ghoseb/389009 to your computer and use it in GitHub Desktop.
Simple bank account code
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
;;; accounts.clj -- Accounts -*- Clojure -*- | |
;;; Time-stamp: "2010-05-04 11:17:53 ghoseb" | |
;;; Author: Baishampayan Ghose <[email protected]> | |
(ns accounts) | |
(def *min-bal* 500) | |
(defstruct account | |
:name | |
:balance) | |
(defn make-account | |
"Create a new account" | |
[name op-balance] | |
;; op-balance should be stored in a ref so that we can modify it in | |
;; a concurrent manner | |
(struct account name (ref op-balance))) | |
(defn account-balance | |
"Get the balance from an account" | |
[acc] | |
@(:balance acc)) | |
(defn account-holder | |
"Get the name of the account holder" | |
[acc] | |
(:name acc)) | |
(defn deposit | |
"Deposit amount into acc" | |
[acc amount] | |
(dosync | |
(commute (:balance acc) + amount))) | |
(defn withdraw | |
"Withdraw amount from acc. Minimum balance is 500" | |
[acc amount] | |
(dosync | |
(let [curr (:balance acc)] | |
(if (> (- @curr amount) *min-bal*) | |
(alter curr - amount) | |
:insufficient-funds)))) | |
(comment | |
(def *acc (make-account "John Doe" 5000)) | |
(deposit *acc 500) | |
(account-balance *acc) | |
(withdraw *acc 20) | |
(account-balance *acc) | |
(binding [*min-bal* 0] | |
(withdraw *acc 5000)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment