Skip to content

Instantly share code, notes, and snippets.

@kirang89
Last active February 29, 2016 17:16
Show Gist options
  • Save kirang89/eab8b7d754b3a8a9586e to your computer and use it in GitHub Desktop.
Save kirang89/eab8b7d754b3a8a9586e to your computer and use it in GitHub Desktop.
Simple example to illustrate the use of refs in Clojure
;;
;; A simple banking system as an example to illustrate refs in Clojure
;;
(def account-a (ref 100))
(def account-b (ref 100))
(defn transfer! [amount from to]
(dosync
(if (>= (- @from amount) 0)
(do
(alter from - amount)
(alter to + amount)))))
(defn deposit! [amount account]
(dosync
(alter account + amount)))
(defn withdraw! [amount account]
(dosync
(if (>= (- @account amount) 0)
(alter account - amount))))
(defn show-balance [account]
(str "Balance: " @account))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment