Skip to content

Instantly share code, notes, and snippets.

@jvoorhis
Created May 12, 2011 22:48
Show Gist options
  • Save jvoorhis/969630 to your computer and use it in GitHub Desktop.
Save jvoorhis/969630 to your computer and use it in GitHub Desktop.
visitor vs catamorphism
class Int
attr_reader :value
def initialize(value)
@value = value
end
def accept(visitor, *data)
visitor.visit_int(self, *data)
end
def fold(rules)
rules[Int].call(value)
end
end
class Add
attr_reader :lhs, :rhs
def initialize(lhs, rhs)
@lhs, @rhs = lhs, rhs
end
def accept(visitor, *data)
visitor.visit_add(self, *data)
end
def fold(rules)
rules[Add].call(lhs.fold(rules), rhs.fold(rules))
end
end
class VisitingInterpreter
def eval(expr)
expr.accept(self)
end
def visit_int(int)
int.value
end
def visit_add(add)
i0 = add.lhs.accept(self)
i1 = add.rhs.accept(self)
i0 + i1
end
end
class CataInterpreter
def eval(expr)
expr.fold(
Int => lambda { |i| i },
Add => lambda { |a,b| a + b }
)
end
end
@sutambe
Copy link

sutambe commented Jul 9, 2014

Can you please elaborate how CataInterpreter works?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment