Queue/Definition: Difference between revisions
Content added Content deleted
(Show error handling) |
(→{{header|Clojure}}: changed in dequeue to if-let to destructure, and reset! to replace the atom's value) |
||
Line 952: | Line 952: | ||
The "pop" function implies mutating the input, but since Clojure data structures are immutable we use a mutable reference to an immutable data structure; in this case an <tt>atom</tt> holding a vector: |
The "pop" function implies mutating the input, but since Clojure data structures are immutable we use a mutable reference to an immutable data structure; in this case an <tt>atom</tt> holding a vector: |
||
<lang |
<lang clojure>(defn make-queue [] |
||
(atom [])) |
(atom [])) |
||
Line 959: | Line 959: | ||
(defn dequeue [q] |
(defn dequeue [q] |
||
(if (seq @q) |
(if-let [[f & r] (seq @q)] |
||
( |
(do (reset! q r) f) |
||
(swap! q subvec 1) |
|||
x) |
|||
(throw (IllegalStateException. "Can't pop an empty queue.")))) |
(throw (IllegalStateException. "Can't pop an empty queue.")))) |
||
Line 968: | Line 966: | ||
(empty? @q))</lang> |
(empty? @q))</lang> |
||
The implementation is thread-safe if there is at most one |
The implementation is thread-safe if there is at most one writer thread, i.e. only one thread ever calls <code>dequeue</code> on a given queue. |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |