Created
March 16, 2016 11:15
-
-
Save christianromney/bb3204f3d30a422a9093 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 brave.core | |
(:require [clojure.core.async :as a | |
:refer [thread go <! >! <!! >!! put! take! chan go-loop alts! timeout close!]])) | |
;; -== From brave clojure ==- | |
(defn hotdog-machine | |
"A hotdog vending machine returns a vector | |
with two channels: input and output. Money | |
should be deposited into the input channel | |
and the output channel will be used for | |
delivery." | |
[hotdogs] | |
(let [in (chan) | |
out (chan)] | |
(go-loop [dogs hotdogs] | |
(if (< 0 dogs) | |
(let [deposit (<! in)] | |
(if (= 3 deposit) | |
(do | |
(>! out :hotdog) | |
(recur (dec dogs))) | |
(do | |
(>! out deposit) | |
(recur dogs)))) | |
(do | |
(close! in) | |
(close! out)))) | |
[in out])) | |
;; -== My Experiments ==- | |
(defn follow! | |
"Follows orders received on the orders channel. | |
Echoes each command with the name of the subordinate then takes some | |
time to accomplish it before actioning the next command." | |
[orders subordinate task-delay] | |
(let [in (chan)] | |
;; follow orders | |
(a/tap orders in) | |
;; execute | |
(go-loop [n 1] | |
(when-let [comm (<! in)] | |
(let [ack (str n "-" subordinate " " comm ", aye!")] | |
(println ack) | |
(Thread/sleep (* task-delay 3)) | |
(recur (inc n))))) | |
in)) | |
(def captain | |
"This channel is where the orders to the crew go in" | |
(chan 10)) | |
(def orders | |
"This is the order multiplexer that allows one order | |
from the captain to be delivered to multiple subordinates" | |
(a/mult captain)) | |
(def xo | |
"The executive officer just repeats orders, so there is very | |
little delay." | |
(follow! orders :xo 1)) | |
(def cob | |
"The chief of the boat actually does stuff, so it takes him | |
a little longer before he's ready to perform the next task." | |
(follow! orders :chief 1000)) | |
(defn give-orders! | |
"Puts orders on a channel" | |
[ch] | |
(a/onto-chan ch [:dive :all-ahead-flank :make-your-depth-60-meters :all-ahead-stop])) | |
(defn -main | |
"Application entry point" | |
[& args] | |
(give-orders! captain)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment