Skip to content

Instantly share code, notes, and snippets.

@mlapshin
Created September 12, 2014 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlapshin/400bcf539dde680f1de1 to your computer and use it in GitHub Desktop.
Save mlapshin/400bcf539dde680f1de1 to your computer and use it in GitHub Desktop.
(ns clojure-async-example.
(:require [clojure.core.async :as async :refer [chan
go go-loop
<! >! >!! <!!
alts! alts!!
timeout
tap mult pub sub
close!]]))
(def max-n 100)
(defn run []
(let [ch (chan)
num (rand-int max-n)]
;; riddler
(go-loop [step 0]
(let [guess (<! ch)]
(cond
(< guess num) (do
(>! ch :greater)
(println "riddler: the number is greater than" guess)
(recur (inc step)))
(> guess num) (do
(>! ch :less)
(println "riddler: the number is less than" guess)
(recur (inc step)))
:else (do
(>! ch :ok)
(println "riddler: BINGO! after" step "steps, bye!")))))
;; guesser
(go-loop [guess (rand-int max-n)]
(>! ch guess)
(println "guesser:" guess)
(let [answer (<! ch)]
(case answer
:ok (println "guesser: bye!")
:less (recur (quot guess 2))
:greater (recur (+ guess 1)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment