Class: Symbolic::Expression

Inherits:
Object
  • Object
show all
Defined in:
lib/symbolic-math.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*tree) ⇒ Expression

Returns a new instance of Expression.



33
34
35
# File 'lib/symbolic-math.rb', line 33

def initialize(*tree)
  @tree = tree
end

Instance Attribute Details

#treeObject (readonly)

Returns the value of attribute tree.



37
38
39
# File 'lib/symbolic-math.rb', line 37

def tree
  @tree
end

Class Method Details

.eval(item, values) ⇒ Object



112
113
114
115
116
117
118
119
# File 'lib/symbolic-math.rb', line 112

def self.eval(item, values)
  case item
    when Expression
      item.eval(values)
    else
      item
  end
end

Instance Method Details

#coerce(other) ⇒ Object



121
122
123
# File 'lib/symbolic-math.rb', line 121

def coerce(other)
  [Expression.new(other), self]
end

#eval(values = {}) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/symbolic-math.rb', line 93

def eval(values={})
  arity = tree.size - 1
  case tree.first
    when Symbol
      if arity==2 && op = INFIX_OPERATORS[tree.first]
        op[Expression.eval(tree[1],values), Expression.eval(tree[2],values)]
      elsif arity==1 && op = PREFIX_OPERATORS[tree.first]
        op[Expression.eval(tree[1],values)]
      elsif (f = FUNCTIONS[tree.first]) && f.arity==arity
        f[*tree[1..-1].map{|x| Expression.eval(x,values)}]
      else
        # assume variable
        values[tree.first] || self
      end
    else
     tree.first
  end
end

#to_sObject



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/symbolic-math.rb', line 75

def to_s
  arity = tree.size - 1
  case tree.first
    when Symbol
      if arity==2 && INFIX_OPERATORS.has_key?(tree.first)
        "(#{tree[1].to_s} #{tree.first} #{tree[2].to_s})"
      elsif arity==1 && PREFIX_OPERATORS.has_key?(tree.first)
        "(#{tree.first} #{tree[1].to_s})"
      elsif (f = FUNCTIONS[tree.first]) && f.arity==arity
        "#{tree.first}(#{tree[1..-1].map{|x| x.to_s}.join(',')})"
      else
        tree.first
      end
    else
     tree.first
  end
end

#varsObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/symbolic-math.rb', line 53

def vars
  vars = []
  if @tree.size==1
    if @tree.first.is_a?(Symbol)
      unless f=FUNCTIONS[@tree.first] && f.arity==0
        vars << @tree.first if @tree.first.is_a?(Symbol)
      end
    end
    # TODO: allow an Expression here?
  else
    @tree[1..-1].each do |subexpr|
      case subexpr
      when Expression
        vars += subexpr.vars
      when Symbol
        vars << subexpr
      end
    end
  end
  vars.uniq
end