Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created May 4, 2010 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghoseb/389009 to your computer and use it in GitHub Desktop.
Save ghoseb/389009 to your computer and use it in GitHub Desktop.
Simple bank account code
;;; accounts.clj -- Accounts -*- Clojure -*-
;;; Time-stamp: "2010-05-04 11:17:53 ghoseb"
;;; Author: Baishampayan Ghose <bg@infinitelybeta.com>
(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