forked from melissavoegeli/threading-in-clojure
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathatoms.clj
48 lines (38 loc) · 2.02 KB
/
atoms.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
; HINT: line 2, 26, and 37
(def my-account {:checking 5})
(defn balance "Print out the balance of the account" [account-hash] (:checking account-hash))
(defn withdrawal
"Subtract from checking balance"
[account-hash amount-to-withdraw] (assoc account-hash :checking (- (:checking account-hash) amount-to-withdraw)))
(defn alert-invalid-withdrawl
"Alert the user that the withdrawl cannot take place"
[] (println "Insufficient funds!"))
(defn withdraw?
"Check if balance is valid and withdraw the amount"
[account-hash amount-to-withdraw] (if (<= amount-to-withdraw (balance account-hash) )
(withdrawal account-hash amount-to-withdraw)
(do
(alert-invalid-withdrawl)
account-hash)))
(defn print-balances
"Print the value known before the swap! happens if it is different from the known global balance"
[known-balance account-changes]
(if-not (= known-balance (balance my-account))
(println (str "Known Balance Beginning of Swap: $" known-balance ", Actual Global Balance: $" (balance my-account)))))
(defn sleep-withdraw-print
"Sleep 1 second then make a withdrawl and print out the balance known before and after"
[account-hash amount-to-withdraw]
(let [known-balance (balance account-hash)]
(Thread/sleep 1000)
(let [account-changes (withdraw? account-hash amount-to-withdraw)]
(print-balances known-balance account-changes)
account-changes)))
(defn swap-values "Calls sleep-withdraw-print on an account atom using swap" [] (sleep-withdraw-print my-account 1))
(defn loop-over
"Given an account, withdraw money however many times is specified"
[account num-of-times amount-to-withdraw]
(doseq [i (range num-of-times)]
(do
(swap-values)
(println "Tried to withdraw $1"))))
(loop-over my-account 10 1)