Wednesday, December 19, 2012

Clojure - From Callbacks to Sequences

I have been spending some hammock time on the problem of converting a stream of events into a sequence.  And Lo and Behold, the answer falls in my lap.  I may need to see if I can implement the pipe function in ClojureScript.  Maybe if I spend more time in the hammock, someone will have already done it.

Be sure and read Clojure - From Callbacks to Sequences for a nice explanation and examples.

Here is the function that does the magic:
(defn pipe
"Returns a vector containing a sequence that will read from the
queue, and a function that inserts items into the queue.
Source: http://clj-me.cgrand.net/2010/04/02/pipe-dreams-are-not-necessarily-made-of-promises/"
[]
(let [q (LinkedBlockingQueue.)
EOQ (Object.)
NIL (Object.)
s (fn queue-seq []
(lazy-seq (let [x (.take q)]
(when-not (= EOQ x)
(cons (when-not (= NIL x) x)
(queue-seq))))))]
[(s) (fn queue-put
([] (.put q EOQ))
([x] (.put q (or x NIL))))]))
view raw pipe.clj hosted with ❤ by GitHub

No comments: