Created
March 15, 2016 19:39
-
-
Save christianromney/f001b74851b94c70ef14 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 subordinate | |
"Sets up a named subordinate of the captain | |
that repeats each received command, then takes some | |
time to accomplish it before actioning the next command." | |
[orders whom task-delay] | |
(let [in (chan)] | |
;; follow orders | |
(a/tap orders in) | |
;; execute | |
(go-loop [n 1] | |
(when-let [comm (<! in)] | |
(let [ack (str whom ": 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." | |
(subordinate 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." | |
(subordinate 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