Last active
February 29, 2016 17:16
-
-
Save kirang89/eab8b7d754b3a8a9586e to your computer and use it in GitHub Desktop.
Simple example to illustrate the use of refs in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; | |
;; 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