global Types type t_item = rec(r : real, i : int, c : char) type t_queue_state = enum(EMPTY, NONEMPTY) end Types global queue import Types op enqueue(val item : t_item) op dequeue(res item : t_item) returns status : t_queue_state body queue() type t_queue_entry = rec(value : t_item; next_entry : ptr t_queue_entry) var head, tail, new_one, old_one : ptr t_queue_entry var count : int := 0 head := tail := new_one := old_one := null write("queue global is alive") proc enqueue(item) new_one := new(t_queue_entry) # no need to check return value of new_one^.value := item # new for null; RTS aborts first new_one^.next_entry := null if tail = null -> # add to an empty queue if head != null -> write("head not null when tail null"); stop fi head := tail := new_one [] else -> # add to end of queue tail^.next_entry := new_one tail := new_one fi count++ write("enqueue: there are now", count, "items in the queue") end enqueue proc dequeue(item) returns status if head = null and tail = null -> status := EMPTY [] head != null and tail != null -> status := NONEMPTY if head = tail -> # dequeue from a singleton queue old_one := head head := tail := null [] else -> # dequeue from beginning of queue old_one := head head := old_one^.next_entry fi item := old_one^.value free(old_one) count-- write("dequeue: there are now", count, "items in the queue") [] else -> write("queue: one of head or tail is null but not other, ERROR"); stop fi end dequeue end queue resource user() import Types import queue procedure get_item_and_print() var item : t_item if queue.dequeue(item) = NONEMPTY -> write("r=", item.r, "i=", item.i, "c=", item.c) [] else -> write("queue is EMPTY") fi end get_item_and_print get_item_and_print() queue.enqueue(t_item(3.1415, 1, 'c')) queue.enqueue(t_item(4.1415, 2, 'd')) queue.enqueue(t_item(5.1415, 3, 'e')) get_item_and_print() get_item_and_print() get_item_and_print() get_item_and_print() queue.enqueue(t_item(6.1415, 4, 'f')) get_item_and_print() queue.enqueue(t_item(7.1415, 5, 'g')) get_item_and_print() get_item_and_print() end user /* ............... Example compile and run(s) % sr -o rque rque.sr % ./rque queue global is alive queue is EMPTY enqueue: there are now 1 items in the queue enqueue: there are now 2 items in the queue enqueue: there are now 3 items in the queue dequeue: there are now 2 items in the queue r= 3.14150 i= 1 c= c dequeue: there are now 1 items in the queue r= 4.14150 i= 2 c= d dequeue: there are now 0 items in the queue r= 5.14150 i= 3 c= e queue is EMPTY enqueue: there are now 1 items in the queue dequeue: there are now 0 items in the queue r= 6.14150 i= 4 c= f enqueue: there are now 1 items in the queue dequeue: there are now 0 items in the queue r= 7.14150 i= 5 c= g queue is EMPTY */