Hi everyone,
Since i was reading about queues these days i decided to write a couple
of functions that would include the basic queue functionality that I
might need when working with queues in Clojure. They are pretty basic
and I've not thoroughly tested them but they seem to behave well...I'm
just posting them here so people can provide feedback in case they'd do
something different...you can be as picky as you like :-) ...
(defn queue
"A (FIFO) queue constructor function. Append (at the rear) with 'conj'
and grab (at the front) with 'peek' (without removal).
This feels more natural to use inside an atom where 'popping' can
return the first element AND also remove it from the queue."
([] clojure.lang.PersistentQueue/EMPTY)
([x] (conj (queue) x))
([x & xs] (into (queue x) xs)) )
(defn push!
"Pushes the x & xs at the rear of the queue q (managed by an atom).
Returns the 'mutated' queue. Thread-safe operation."
([q x] (swap! q conj x))
([q x & xs]
(swap! q #(into (conj % x) xs))))
(defn peek+pop!
"Removes the 1st item from the queue q (managed by an atom) and returns
it. Thread-safe operation."
[q]
(loop []
(let [[head & r :as l] @q]
(if (compare-and-set! q l (pop l)) head
(recur)))))
--------------------------------------------------------------------------------------------------------------------------------------
any feedback is welcome and appreciated...One thing I don't have so far
is the ability to create queues from other data-structures (just like
'vec') but I can see that there exists a constructor that has that
facility so that should be easy to do...
thanks in advance :-)
Jim
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en