Mercurial > repos > other > SevenLanguagesInSevenWeeks
comparison 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 |
comparison
equal
deleted
inserted
replaced
84:920b50be0fe5 | 85:67e2bb3bcccd |
---|---|
1 (def accounts (ref [])) | |
2 | |
3 (defn add_account [accts] | |
4 (dosync (alter accts conj 0))) | |
5 | |
6 (defn credit [accts acct_num amount] | |
7 (dosync | |
8 (alter accts assoc acct_num (+ (accts acct_num) amount)) | |
9 ) | |
10 ) | |
11 | |
12 (defn debit [accts acct_num amount] | |
13 (dosync | |
14 (alter accts assoc acct_num (- (accts acct_num) amount)) | |
15 ) | |
16 ) | |
17 | |
18 (defn transfer [accts acct_from acct_to amount] | |
19 (dosync | |
20 (debit accts acct_from amount) | |
21 (credit accts acct_to amount) | |
22 ) | |
23 ) | |
24 | |
25 (add_account accounts) | |
26 (add_account accounts) | |
27 (add_account accounts) | |
28 (credit accounts 0 100) | |
29 (credit accounts 1 50) | |
30 (credit accounts 2 500) | |
31 (transfer accounts 2 1 150) | |
32 (println @accounts) ; We should get [100, 200, 350] |