Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created March 7, 2018 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/19c88ca271b162d97d9e594b670da0a0 to your computer and use it in GitHub Desktop.
Save rklemme/19c88ca271b162d97d9e594b670da0a0 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
OPS = {}
def OPS.[](cmd, *arg)
self.fetch([cmd, arg.first.class])[*arg]
end
Constant = Struct.new(:value) do
def initialize(v)
self[:value] = v.to_f
end
end
BinaryPlus = Struct.new :lhs, :rhs
OPS[[:stringify, Constant]] = lambda {|c| v.value.to_s}
OPS[[:stringify, BinaryPlus]] = lambda {|c| "#{OPS[:stringify, lhs]} + #{OPS[:stringify, c.rhs]}"}
OPS[[:evaluate, Constant]] = lambda {|c| c.value}
OPS[[:evaluate, BinaryPlus]] = lambda {|c| OPS[:evaluate, c.lhs] + OPS[:evaluate, c.rhs]}
tree = BinaryPlus[Constant[1.2], Constant[2.5]]
p tree
puts OPS[:evaluate, tree]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment