Skip to content

Instantly share code, notes, and snippets.

@jsuchal
Created July 7, 2014 07:15
Show Gist options
  • Save jsuchal/d4c2361da67615d6ae28 to your computer and use it in GitHub Desktop.
Save jsuchal/d4c2361da67615d6ae28 to your computer and use it in GitHub Desktop.
class Number < Struct.new(:value)
def print
value
end
end
class Binary < Struct.new(:left, :right)
end
class Plus < Binary
def print
"(#{left.print} + #{right.print})"
end
end
class Times < Binary
def print
"(#{left.print} * #{right.print})"
end
end
expression = Plus.new(
Number.new(1),
Times.new(Number.new(2), Number.new(5))
)
puts expression.print
class Negation < Struct.new(:expression)
def print
"-#{expression.print}"
end
end
expression = Plus.new(
Number.new(1),
Times.new(Number.new(2), Negation.new(Number.new(5)))
)
puts expression.print
# dev3
# jankos_evaluations
class Number
def eval
value
end
end
class Plus
def eval
left.eval + right.eval
end
end
class Times
def eval
left.eval * right.eval
end
end
class Negation
def eval
-expression.eval
end
end
puts expression.eval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment