Created
December 15, 2016 01:14
-
-
Save philip-doctor/5717313832a9077abfc4330f05b0c16a to your computer and use it in GitHub Desktop.
Example of one way to try to structure clojure code by creating a compositional root, and then a stateful layer around a core of pure functions
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
(ns customer-bank.core | |
(:require | |
[clojure.core.async :as async :refer [go timeout close! put! chan <! >!! go-loop]]) | |
(:gen-class)) | |
(defrecord TransactionLog [action account-number data]) | |
(defn add-to-bank-account [bank-balance deposit-amount] | |
(let [new-balance (+ bank-balance deposit-amount)] | |
(prn new-balance) | |
new-balance)) | |
(defn event-loop [event-channel all-bank-accounts] | |
(go-loop [[action account-number data] (<! event-channel)] | |
(let [customer-balance (get @all-bank-accounts account-number) | |
new-balance | |
(cond | |
(= action :deposit) (add-to-bank-account customer-balance data))] | |
(swap! all-bank-accounts assoc account-number new-balance)) | |
(recur (<! event-channel)))) | |
(defn -main | |
"I don't do a whole lot ... yet." | |
[& args] | |
(let [event-channel (chan 50) | |
_ (>!! event-channel [:deposit :12345 10]) | |
all-bank-accounts (atom {:12345 100 | |
:98765 200})] | |
(event-loop event-channel all-bank-accounts) | |
(>!! event-channel [:deposit :12345 20]) | |
(Thread/sleep 10000))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment