Class: LambdaGem::Expression

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression = nil, order = :infix, dictionary = nil) ⇒ Expression

Returns a new instance of Expression.



8
9
10
11
12
13
# File 'lib/expression.rb', line 8

def initialize expression=nil, order=:infix, dictionary=nil     
  order = :infix if !@@AVAILABLE_ORDERING.include? order
  @dictionary = Dictionary.new
  @formula, @current_order, @tree = expression, order, Tree.new
  tree_from_expression(expression,order) if !expression.nil?
end

Instance Attribute Details

#current_orderObject

Returns the value of attribute current_order.



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

def current_order
  @current_order
end

#dictionaryObject

Returns the value of attribute dictionary.



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

def dictionary
  @dictionary
end

#treeObject

Returns the value of attribute tree.



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

def tree
  @tree
end

Instance Method Details

#evaluateObject



63
64
65
# File 'lib/expression.rb', line 63

def evaluate
 eval(@tree.root)
end

#formulaObject



15
16
17
# File 'lib/expression.rb', line 15

def formula
 @formula
end

#formula=(new_expression) ⇒ Object



19
20
21
22
# File 'lib/expression.rb', line 19

def formula= new_expression
  tree_from_expression new_expression
  @formula = new_expression
end

#operator?(token) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/expression.rb', line 59

def operator?(token)
 @dictionary.contains?(token.to_s)
end

#tree_from_expression(expression = @formula, order = :infix) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/expression.rb', line 24

def tree_from_expression expression=@formula, order=:infix
  tokens = tokenize expression
  operator_stack, node_stack = [], []

  tokens.each do |token|
    token = token.downcase

    if operator?(token)
      until(operator_stack.empty? or
            operator_stack.last.data == "(" or
            @dictionary.operator_priority[operator_stack.last.data] < @dictionary.operator_priority[token])
        pop_connect_push operator_stack, node_stack
      end
      operator_stack.push(Node.new(token))
    elsif token == "("
      operator_stack.push(Node.new(token))
    elsif token == ")"
      while operator_stack.last.data != "("
        pop_connect_push operator_stack, node_stack
      end
      operator_stack.pop #throw '('
    else
      node_stack.push(Node.new(token))
    end

  end

  until operator_stack.empty?
    pop_connect_push operator_stack, node_stack
  end

  @tree.root = node_stack.last
  @tree
end