Created
March 15, 2016 19:43
-
-
Save christianromney/c78e4c3bb4e26e5860ce 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 subordinate ": order " n ", " comm ", aye!")] | |
(println ack) | |
(Thread/sleep (* task-delay (rand-int 10))) | |
(recur (inc n))))) | |
in)) | |
(def captain | |
"This channel is where the orders to the crew go in" | |
(chan)) | |
(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] | |
(>!! ch :dive) | |
(>!! ch :all-ahead-flank) | |
(>!! ch :make-your-depth-60-meters) | |
(>!! ch :all-ahead-stop) | |
ch) | |
(defn -main | |
"Application entry point" | |
[& args] | |
(-> captain give-orders! close!)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment