Skip to content

Instantly share code, notes, and snippets.

@csivanich
Last active August 29, 2015 14:24
Show Gist options
  • Save csivanich/3e7cd846fad770d4a8df to your computer and use it in GitHub Desktop.
Save csivanich/3e7cd846fad770d4a8df to your computer and use it in GitHub Desktop.
Math Object Model Example
#!/usr/bin/env ruby
# Chris Sivanich 2015
class Node
def initialize
end
def to_s
end
def evaluate
end
end
class MinusNode < Node
def initialize(left, right)
@left = left
@right = right
end
def to_s
return "(#{@left} - #{@right})"
end
def evaluate
return @left.evaluate() - @right.evaluate()
end
end
class IntNode < Node
def initialize(value)
@value = value
end
def to_s
return @value
end
#WARN only int
def evaluate
return @value
end
end
class MultNode < Node
def initialize(left, right)
@left = left
@right = right
end
def to_s
return "(#{@left} * #{@right})"
end
def evaluate
return @left.evaluate() * @right.evaluate()
end
end
class PlusNode < Node
def initialize(left, right)
@left = left
@right = right
end
def to_s
return "(#{@left} + #{@right})"
end
def evaluate
return @left.evaluate() + @right.evaluate()
end
end
class IntNode < Node
def initialize(value)
@value = value
end
def to_s
return @value.to_s
end
def evaluate
return @value
end
end
# Start main script here
#
# Completely necessary at some point, but clearer to declare ahead of time
one = IntNode.new(1)
two = IntNode.new(2)
three = IntNode.new(3)
# More pretty objects
one_plus_two = PlusNode.new(one, two)
three_minus_one = MinusNode.new(three, one)
five_times_five = MultNode.new(IntNode.new(5), IntNode.new(5))
expr = PlusNode.new(PlusNode.new(one_plus_two, three_minus_one), five_times_five)
# (((1 + 2) + (3 - 1)) + (5 * 5))
puts expr.to_s
# 30
puts expr.evaluate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment