Queue/Definition: Difference between revisions
→{{header|jq}}
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 3,761:
=={{header|jq}}==
The approach taken here is to use a JSON object with a key named "queue"
to hold the contents of the queue. This allows us to "pop" a queue by modifying
.queue while returning the popped item in the same object under a different key.
<syntaxhighlight lang="jq"># An empty queue:▼
There are three possibilities for defining `pop` on an empty queue:
def push(e): [e] + .;▼
# Do not make a special case of it, which in our case would mean that `{queue: []} | pop` would emit `{queue: [], item: null}`
# Raise an error
# Emit nothing
Here (1), is questionable as the queue might contain null, so here we define
def pop_or_error: if length == 0 then error("pop_or_error") else pop end;▼
`pop_or_error`, which raises an error when given an empty queue, and `pop`, which
emits the empty stream when given an empty queue.
In order to facilitate observing the evolving states of queues during processing,
we use the same `observe` function defined at [[Stack]].
def empty: length == 0;</syntaxhighlight>▼
# Input: an object
'''Examples''':▼
# Output: the updated object with .emit filled in from `update|emit`.
# `emit` may produce a stream of values, which need not be strings.
def observe(update; emit):
def s(stream): reduce stream as $_ (null;
if $_ == null then .
elif . == null then "\($_)"
else . + "\n\($_)"
end);
.emit as $x
| update
| .emit = s($x // null, emit);
fifo▼
| pop # dequeue▼
def fifo
# Is the input an object that represents the empty queue?
def isempty:
type == "object"
and (.queue | length == 0); # so .queue == null and .queue == [] are equivalent
def pop: if isempty then empty else .item = .queue[0] | .queue |= .[1:] end;
# fifo | pop // "nothing" # produces the string "nothing"
▲fifo
| observe(push(42); "length after pushing: \(.queue | length)" )
| observe(push(43); "length after pushing: \(.queue | length)" )
| .emit, .item
'''Output'''
<pre>
length after pushing: 1
length after pushing: 2
42
</pre>
=={{header|Julia}}==
|