Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save reddavis/110756 to your computer and use it in GitHub Desktop.
Save reddavis/110756 to your computer and use it in GitHub Desktop.
class FWrapper
attr_reader :function, :params, :name
def initialize(function, params, name)
@function = function
@params = params
@name = name
end
end
class Node
attr_reader :function, :children, :name
def initialize(fw, children)
@function = fw.function
@name = fw.name
@children = children
end
def evaluate(inp)
results = children.inject([]) {|ary, n| ary << n.evaluate(inp)}
function.call(results)
end
def display(indent=0)
puts ' '*indent + name
children.each {|c| c.display(indent+1)}
end
end
class ParamNode
attr_reader :idx
def initialize(idx)
@idx = idx
end
def evaluate(inp)
inp[idx]
end
def display(indent=0)
puts ' '*indent + idx.to_s
end
end
class ConstNode
attr_reader :v
def initialize(v)
@v = v
end
def evaluate(inp)
v
end
def display(indent=0)
puts ' '*indent + v.to_s
end
end
addw = FWrapper.new(lambda {|x| x[0] + x[1]}, 2, 'add')
subw = FWrapper.new(lambda {|x| x[0] - x[1]}, 2, 'subtract')
mulw = FWrapper.new(lambda {|x| x[0] * x[1]}, 2, 'multiply')
iffunc = lambda do |x|
if x[0] > 0
return x[1]
else
return x[2]
end
end
isgreater = lambda do |x|
if x[0] > x[1]
return 1
else
return 0
end
end
ifw = FWrapper.new(iffunc, 3, 'if')
gtw = FWrapper.new(isgreater, 2, 'isgreater')
flist = [addw, subw, mulw, ifw, gtw]
example_tree = Node.new(ifw, [
Node.new(gtw, [ParamNode.new(0), ConstNode.new(3)]),
Node.new(addw, [ParamNode.new(1), ConstNode.new(5)]),
Node.new(subw, [ParamNode.new(1), ConstNode.new(2)])
])
example_tree.display
puts example_tree.evaluate([5,3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment