changeset 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 920b50be0fe5
children ab08b4bcd4a9
files 6-Clojure/banking.clj
diffstat 1 files changed, 32 insertions(+), 0 deletions(-) [+]
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]