Skip to content

Instantly share code, notes, and snippets.

@narma
Forked from anonymous/search_fastest.clj
Created April 25, 2014 18:57
Show Gist options
  • Save narma/11299576 to your computer and use it in GitHub Desktop.
Save narma/11299576 to your computer and use it in GitHub Desktop.
(use 'clojure.core.async)
(defn req [server query]
(go
(<! (timeout (rand-int 100)))
(str query " from " server)))
(defn fastest [query & servers]
(let [c (chan)]
(doseq [server servers]
(go
(>! c (<! (req server query)))
(close! c)))
c))
;; go returns channel with return value
(defn search [query t]
(let [c (chan)
t (timeout t)]
(go (>! c (<! (fastest query "web1" "web2" "web3"))))
(go (>! c (<! (fastest query "img1" "img2"))))
(go (>! c (<! (fastest query "video1" "video2"))))
(go-loop [ret []]
(if (>= (count ret) 3)
ret
(recur
(conj ret (alt! [c t] ([v] v))))))))
(<!! (search "abc" 90))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment