view 6-Clojure/banking.clj @ 103:98be775c533c default tip

An odd "non-determinism" example from StackOverflow It is clever, but doesn't make much sense as to how it gets its results
author IBBoard <dev@ibboard.co.uk>
date Sun, 14 Jul 2019 13:44:13 +0100
parents 67e2bb3bcccd
children
line wrap: on
line source

(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]