Class: BinaryParser::Expression

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rpn) ⇒ Expression

Returns a new instance of Expression.



5
6
7
# File 'lib/general_class/expression.rb', line 5

def initialize(rpn)
  @rpn = rpn
end

Instance Attribute Details

#rpnObject (readonly)

Returns the value of attribute rpn.



3
4
5
# File 'lib/general_class/expression.rb', line 3

def rpn
  @rpn
end

Instance Method Details

#*(other) ⇒ Object



17
18
19
# File 'lib/general_class/expression.rb', line 17

def *(other)
  return Expression.new(@rpn + to_rpn(other) + [:__mul])
end

#+(other) ⇒ Object



9
10
11
# File 'lib/general_class/expression.rb', line 9

def +(other)
  return Expression.new(@rpn + to_rpn(other) + [:__add])
end

#-(other) ⇒ Object



13
14
15
# File 'lib/general_class/expression.rb', line 13

def -(other)
  return Expression.new(@rpn + to_rpn(other) + [:__sub])
end

#/(other) ⇒ Object



21
22
23
# File 'lib/general_class/expression.rb', line 21

def /(other)
  return Expression.new(@rpn + to_rpn(other) + [:__div])
end

#eval(&name_eval_block) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/general_class/expression.rb', line 41

def eval(&name_eval_block)
  stack, rpn = [], @rpn.dup
  until rpn.empty?
    stack << rpn.shift
    case stack.last
    when :__add
      arg = [stack.pop, stack.pop, stack.pop]
      stack << arg[2] + arg[1]
    when :__sub
      arg = [stack.pop, stack.pop, stack.pop]
      stack << arg[2] - arg[1]
    when :__mul
      arg = [stack.pop, stack.pop, stack.pop]
      stack << arg[2] * arg[1]
    when :__div
      arg = [stack.pop, stack.pop, stack.pop]
      stack << arg[2] / arg[1]
    when Symbol
      stack << name_eval_block.call(stack.pop)
    end
  end
  raise ProgramAssertionError, "Cannot calc RPN." unless stack.length == 1
  return stack.last
end

#to_rpn(other) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/general_class/expression.rb', line 25

def to_rpn(other)
  case other
  when Integer
    return [other]
  when Expression
    return other.rpn
  else
    raise BadManipulationError, "Unknown type of other (#{other.class})."
  end
end

#variablesObject



36
37
38
39
# File 'lib/general_class/expression.rb', line 36

def variables
  control_symbols = [:__add, :__sub, :__mul, :__div]
  return @rpn.select{|token| token.is_a?(Symbol) && !control_symbols.include?(token)}
end