Queue/Definition: Difference between revisions

Content added Content deleted
(→‎{{header|Clojure}}: changed in dequeue to if-let to destructure, and reset! to replace the atom's value)
(Added Bracmat example)
Line 658:
Error: queue empty
</pre>
 
 
=={{header|Bracmat}}==
Below, <code>queue</code> is the name of a class with a data member <code>list</code> and three methods <code>enqueue</code>, <code>dequeue</code> and <code>empty</code>.
 
No special provision is implemented to "throw and exception" in case you try to dequeue from and empty queue, because, in Bracmat, evaluation of an expression, besides resulting in an evaluated expression, always also either "succeeds" or "fails". (There is, in fact, a third possibility, "ignore", telling Bracmat to close an eye even though an evaluation didn't succeed.) So in the example below, the last dequeue operation fails and the program continues on the right hand side of the bar (<code>|</code>) operator
<lang bracmat> ( queue
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
( dequeue
= x
. !(its.list):?(its.list) (.?x)
& !x
)
(empty=.!(its.list):)
)</lang>
 
Normally you would seldom use a class as depicted above, because the operations are so simple that you probably use them directly. Bracmat lists allow prepending as well as appending elements, and single elements can be removed from the beginning or from the end of a list.
 
Appending an element to a long list and removing an element from the end of a long list are quite expensive operations, with a cost <i>O</i>(<i>n</i>), where <i>n</i> is the number of elements in the queue.
 
 
=={{header|C}}==