Created
May 12, 2011 22:48
-
-
Save jvoorhis/969630 to your computer and use it in GitHub Desktop.
visitor vs catamorphism
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please elaborate how CataInterpreter works?