Class: ImmutableQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/ImmutableQueue.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.emptyObject



23
24
25
# File 'lib/ImmutableQueue.rb', line 23

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

Instance Method Details

#popObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/ImmutableQueue.rb', line 7

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

#push(element) ⇒ Object



2
3
4
5
# File 'lib/ImmutableQueue.rb', line 2

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

#push_array(arr) ⇒ Object



27
28
29
30
31
# File 'lib/ImmutableQueue.rb', line 27

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