Skip to content

Instantly share code, notes, and snippets.

@claj
Last active December 19, 2015 15:19
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 claj/5975507 to your computer and use it in GitHub Desktop.
Save claj/5975507 to your computer and use it in GitHub Desktop.
(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