Queue/Definition: Difference between revisions
Content deleted Content added
Added Scheme |
→{{header|Ruby}}: Add RDoc comments and a few more aliases. Usage remains as before. |
||
Line 2,138: | Line 2,138: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
The core class ''Array'' already implements all queue operations, so this class ''FIFO'' delegates everything to methods of ''Array''. |
|||
⚫ | |||
⚫ | |||
<lang ruby>require 'forwardable' |
|||
@fifo = [] |
|||
# A FIFO queue contains elements in first-in, first-out order. |
|||
# FIFO#push adds new elements to the end of the queue; |
|||
# FIFO#pop or FIFO#shift removes elements from the front. |
|||
⚫ | |||
extend Forwardable |
|||
# Creates a FIFO containing _objects_. |
|||
def self.[](*objects) |
|||
⚫ | |||
end |
end |
||
⚫ | |||
# Creates an empty FIFO. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
# Appends _objects_ to the end of this FIFO. Returns self. |
|||
⚫ | |||
@ary.push(*objects) |
|||
self |
self |
||
end |
end |
||
Line 2,150: | Line 2,164: | ||
alias enqueue push |
alias enqueue push |
||
⚫ | |||
# popping an empty FIFO returns nil, or [] if a number is specified |
|||
# :method: pop |
|||
# :call-seq: |
|||
@fifo.shift(*args) |
|||
# pop -> obj or nil |
|||
end |
|||
# pop(n) -> ary |
|||
# |
|||
# Removes an element from the front of this FIFO, and returns it. |
|||
⚫ | |||
# Returns nil if the FIFO is empty. |
|||
# |
|||
# If passing a number _n_, removes the first _n_ elements, and returns |
|||
# an Array of them. If this FIFO contains fewer than _n_ elements, |
|||
# returns them all. If this FIFO is empty, returns an empty Array. |
|||
def_delegator :@ary, :shift, :pop |
|||
alias shift pop |
|||
alias dequeue shift |
|||
## |
|||
# :method: empty? |
|||
# Returns true if this FIFO contains no elements. |
|||
def_delegator :@ary, :empty? |
|||
## |
|||
⚫ | |||
# Returns the number of elements in this FIFO. |
|||
def_delegator :@ary, :size |
|||
alias length size |
|||
# Converts this FIFO to a String. |
|||
⚫ | |||
⚫ | |||
@fifo.length |
|||
"FIFO#{@ary.inspect}" |
|||
end |
end |
||
alias inspect to_s |
|||
end |
|||
end</lang> |
|||
f = FIFO.new |
<lang ruby>f = FIFO.new |
||
f.empty? # => true |
f.empty? # => true |
||
f.pop # => nil |
f.pop # => nil |
||
f.pop(2) # => [] |
f.pop(2) # => [] |
||
f.push(14) # => |
f.push(14) # => FIFO[14] |
||
f << "foo" << [1,2,3] # => |
f << "foo" << [1,2,3] # => FIFO[14, "foo", [1, 2, 3]] |
||
f.enqueue("bar", Hash.new, "baz") |
f.enqueue("bar", Hash.new, "baz") |
||
# => FIFO[14, "foo", [1, 2, 3], "bar", {}, "baz"] |
|||
f.size # => 6 |
f.size # => 6 |
||
f.pop(3) # => [14, "foo", [1, 2, 3]] |
f.pop(3) # => [14, "foo", [1, 2, 3]] |
||
f.dequeue # => "bar" |
f.dequeue # => "bar" |
||
f.empty? # => false |
f.empty? # => false |
||
g = FIFO[:a, :b, :c] |
|||
g.pop(2) # => [:a, :b] |
|||
g.pop(2) # => [:c] |
|||
g.pop(2) # => []</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |