Clojure: Refs example for bank transaction

299 views Asked by At

I am still noob at Clojure, right know I am trying to resolve a problem involving bank transaction scenario for university.

The problem is quite easy: I have to develop a solution to credit, debit and transfer money.

I stopped here:

(def account
    (ref 100))

(defn credit [account amount]
  "Credit"
  (dosync
    (alter account + amount)))


(defn debit [account amount]
  "Debit"
  (dosync
    (if (> amount (balance account))
      (throw (Exception. "Insuficient Funds"))
      (alter account - amount))))

(defn transfer [from to amount]
  "Transfer"
  (dosync
    (if (<= amount (balance from)) 
      (do 
        (Thread/sleep 10)
        (debit from amount)


        (credit to amount))
      (throw
        (Exception. "Insuficient Funds")))))

I think its nothing to hard to understand and the code above is working.

I should add the account number, description of the transaction, data and amount and storage in memory in each function above like:

 (defn credit [account description data amount]
  "Credit"
  (dosync
    (alter account + amount)))

I have tried with hash-map, vectors and other things but didn't work. Also I am trying to find this solution in this book: Clojure Programming O'reilly, but still difficult to implement.

Thank you for your time and let me know if you need more infos.

1

There are 1 answers

0
junis087678 On BEST ANSWER

I think I found a way to develop this scenario.

When creating an bank account I am using refs and a structure to save all data needed (name account, number account and a operation list with all transactions that will be created)

(defn create-account [name account-number]
  "Create account"
  (ref (merge {:name name :account-number account-number :operations '()})))

(def joey 
  "Account for tests"
  (create-account "joey" 12345678))