class MathPrograms::E10P::Node

Node is a node in an expression.

Example: 2+3*4

The expression above has two nodes, + and *. It is implemented as follows in the program.

  +
 / \
2   *
   / \
  3   4

The node at the bottom has operator * and numbers 3 and 4. The result is twelve. It has three elements @op, @a and @b, which are correspond to *, 3 and 4. Let this node be “X”. The node at the top has *, 2 and a node X.

Attributes

a[RW]
b[RW]
op[RW]

Public Class Methods

new(op, a, b) click to toggle source
# File lib/math_programs/e10p.rb, line 56
def initialize op, a, b
  @op, @a, @b = op, a, b
end

Public Instance Methods

to_s() click to toggle source
# File lib/math_programs/e10p.rb, line 73
def to_s
  if @op == "*" || @op == "/"
    if @a.is_a?(Node) && (@a.op == "+" || @a.op == "-")
      a = "(#{@a})"
    else
      a = "#{@a}"
    end
    if @b.is_a?(Node) && (@b.op == "+" || @b.op == "-" || @op == "/")
      b = "(#{@b})"
    else
      b = "#{@b}"
    end
  elsif @op == "-" && @b.is_a?(Node) && (@b.op == "+" || @b.op == "-")
    a = "#{@a}"
    b = "(#{@b})"
  else
    a = "#{@a}"
    b = "#{@b}"
  end
  a+@op+b
end
value() click to toggle source
# File lib/math_programs/e10p.rb, line 59
def value
  case @op
  when "+"
    @a.value + @b.value
  when "-"
    @a.value - @b.value
  when "*"
    @a.value * @b.value
  when "/"
    Rational(@a.value, @b.value) if @b.value != 0
  else
    nil
  end
end