Anonymous user
Queue/Definition: Difference between revisions
Removed "import queues" as module no longer exists. Added description of queue and basic operations. Added try..except when popping from empty queue.
Drkameleon (talk | contribs) (obsolete) |
(Removed "import queues" as module no longer exists. Added description of queue and basic operations. Added try..except when popping from empty queue.) |
||
Line 3,626:
=={{header|Nim}}==
<lang nim>
Node[T] = ref object
value: T
proc push*[T](q: var TQueue[T]; item: T) =▼
proc pop*[T](q: var TQueue[T]): T =▼
Queue*[T] = object
var fifo: TQueue[int] = initQueue[int]()▼
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo
echo
echo
echo
try:
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()</lang>
{{out}}
<pre>Fifo size: 3
Popping: 26
Popping: 99
Popping: 2
Exception catched: popping from empty queue.</pre>
=={{header|OCaml}}==
|