Sha256: 602ed3ec68a8bb9956f9dd5b21ff56217dc5efda1be184c713960ddaae379112

Contents?: true

Size: 887 Bytes

Versions: 1

Compression:

Stored size: 887 Bytes

Contents

class ImmutableQueue
  def push(element)
    b = (back or ImmutableStack.empty)
    ImmutableQueue.new(front, b.push(element))
  end

  def pop()
    f, b = front, back
    if (f == ImmutableStack.empty) then
      until (b == ImmutableStack.empty) do
        (e, b = b.pop
        f = f.push(e))
      end
    end
    head, f = f.pop
    if (f == b) then
      [head, ImmutableQueue.empty]
    else
      [head, ImmutableQueue.new(f, b)]
    end
  end

  def self.empty()
    @@empty ||= ImmutableQueue.new(ImmutableStack.empty, ImmutableStack.empty)
  end

  def push_array(arr)
    q = self
    arr.each { |i| q = q.push(i) } if arr
    q
  end

  private
  def initialize(front, back)
    @front = (front or ImmutableStack.empty)
    @back = (back or ImmutableStack.empty)
    self.freeze
  end

  attr_reader :front
  attr_reader :back

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
maroon-0.7.1 lib/ImmutableQueue.rb