Guest User

Untitled

a guest
Nov 19th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. ============================== channels ==========================
  2.  
  3. (require '[clojure.core.async :as async :refer :all])
  4.  
  5. (let [c1 (chan)
  6. c2 (chan)]
  7. (go (while true
  8. (let [[v ch] (alts! [c1 c2])]
  9. (println "Read" v "from" ch))))
  10. (go (>! c1 "hi"))
  11. (go (>! c2 "there")))
  12.  
  13. ========================= extended channels example ==============
  14.  
  15. (defn fake-search [kind]
  16. (fn [c query]
  17. (go
  18. (<! (timeout (rand-int 100)))
  19. (>! c [kind query]))))
  20.  
  21. (def web1 (fake-search :web1))
  22. (def web2 (fake-search :web2))
  23. (def image1 (fake-search :image1))
  24. (def image2 (fake-search :image2))
  25. (def video1 (fake-search :video1))
  26. (def video2 (fake-search :video2))
  27.  
  28. (defn fastest [query & replicas]
  29. (let [c (chan)]
  30. (doseq [replica replicas]
  31. (replica c query))
  32. c))
  33.  
  34. (defn google [query]
  35. (let [c (chan)
  36. t (timeout 80)]
  37. (go (>! c (<! (fastest query web1 web2))))
  38. (go (>! c (<! (fastest query image1 image2))))
  39. (go (>! c (<! (fastest query video1 video2))))
  40. (go (loop [i 0 ret []]
  41. (if (= i 3)
  42. ret
  43. (recur (inc i) (conj ret (alt! [c t] ([v] v)))))))))
  44.  
  45. (<!! (google "clojure"))
Add Comment
Please, Sign In to add comment