Skip to content

Instantly share code, notes, and snippets.

@JoergWMittag
Created December 15, 2010 04:27
Show Gist options
  • Save JoergWMittag/741630 to your computer and use it in GitHub Desktop.
Save JoergWMittag/741630 to your computer and use it in GitHub Desktop.
# We want a uniform way of reducing a code tree
# so the easiest way to do that is to extend
# Object with a call method and whenever any
# object does not define it's own call method we
# assume the object is implicitly claiming it wants
# to return itself. Since Object is almost at the top
# of the hierarchy almost anything we are interested
# in will work as expected.
class Object
def call
self
end
end
# The children of an instance of a CodeTree consist either
# of more CodeTree instances or just some objects which we
# will pass to the root when it's time to reduce the tree and
# get a value out of it
class CodeTree
def initialize(proc, *children)
@proc, @children = proc, children
end
def call
@proc.(*@children.map(&:call))
end
end
plus = ->(a, b) { a + b }
code_tree = CodeTree.new(plus, 1, CodeTree.new(plus, 1, 1))
code_tree.() # ==> 1+(1+1) ==> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment