Mercurial > repos > other > SevenLanguagesInSevenWeeks
diff 6-Clojure/banking.clj @ 85:67e2bb3bcccd
Add bank account processing with refs and dosync calls
Also included a "transfer" function to atomically transfer money.
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sun, 09 Jun 2019 19:47:01 +0100 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/6-Clojure/banking.clj Sun Jun 09 19:47:01 2019 +0100 @@ -0,0 +1,32 @@ +(def accounts (ref [])) + +(defn add_account [accts] + (dosync (alter accts conj 0))) + +(defn credit [accts acct_num amount] + (dosync + (alter accts assoc acct_num (+ (accts acct_num) amount)) + ) +) + +(defn debit [accts acct_num amount] + (dosync + (alter accts assoc acct_num (- (accts acct_num) amount)) + ) +) + +(defn transfer [accts acct_from acct_to amount] + (dosync + (debit accts acct_from amount) + (credit accts acct_to amount) + ) +) + +(add_account accounts) +(add_account accounts) +(add_account accounts) +(credit accounts 0 100) +(credit accounts 1 50) +(credit accounts 2 500) +(transfer accounts 2 1 150) +(println @accounts) ; We should get [100, 200, 350]