Last active
December 19, 2015 15:19
-
-
Save claj/5975507 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 async-math) | |
(require '[clojure.core.async :as async :refer :all]) | |
(defn query-maker | |
"generates a simple math-query and the answer to it" | |
[] | |
(let [a (rand-int 10) b (rand-int 10)] | |
{:query (str "what is " a " + " b "?") | |
:answer (+ a b)})) | |
;; {:query "what is 1 + 2 ?" :answer 3} | |
;; an un-buffered channel: | |
(def answer-chan (chan)) | |
(future ;;to let go of the repl | |
(go ;;start async transaction | |
(while true ;; run forever | |
(let [task (query-maker)] ;; create a task | |
(println (:query task)) ;; output query (apparently this could be put in a channel) | |
(if (== (<! answer-chan) (:answer task)) ;;wait for a new entry in answer-chan | |
(println "correct!") | |
(println "wrong")))))) | |
;;short helper for answering | |
(defn ans [x] | |
(>!! answer-chan x)) | |
;;the REPL interaction becames: | |
;;what is 2 + 7? | |
;;async-math> (ans 9) | |
;;correct! | |
;;what is 0 + 5? | |
;;async-math> (ans 10) | |
;;wrong! | |
;;what is 3 + 3? | |
;;async-math> _ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment