Sha256: 9c6801c7022ed01d00cedb13b6ffff2381f1c21a99fda8a547deedbfeac46c69

Contents?: true

Size: 983 Bytes

Versions: 2

Compression:

Stored size: 983 Bytes

Contents

require 'hamster/list'

module Hamster

  def self.stack(*items)
    items.reduce(EmptyStack) { |stack, item| stack.push(item) }
  end

  class Stack

    def initialize(list)
      @list = list
    end

    def empty?
      @list.empty?
    end

    def size
      @list.size
    end
    alias_method :length, :size

    def top
      @list.head
    end

    def push(item)
      self.class.new(@list.cons(item))
    end
    alias_method :<<, :push

    def pop
      list = @list.tail
      if list.empty?
        EmptyStack
      else
        self.class.new(list)
      end
    end

    def clear
      EmptyStack
    end

    def eql?(other)
      return true if other.equal?(self)
      return false unless other.class.equal?(self.class)
      @list.eql?(other.instance_eval{@list})
    end
    alias_method :==, :eql?

    def dup
      self
    end
    alias_method :clone, :dup

    def inspect
      @list.inspect
    end

  end

  EmptyStack = Stack.new(Hamster.list)

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hamster-0.1.21 lib/hamster/stack.rb
hamster-0.1.20 lib/hamster/stack.rb