Skip to content

Instantly share code, notes, and snippets.

@mwcampbell
Created October 1, 2011 20:00
Show Gist options
  • Save mwcampbell/1256577 to your computer and use it in GitHub Desktop.
Save mwcampbell/1256577 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
class Expr {
public:
virtual ~Expr() { }
virtual int eval() = 0;
};
class Literal : public Expr {
int x;
public:
Literal(int val): x(val) { }
virtual int eval() { return x; }
};
class PlusExpr : public Expr {
Expr* a;
Expr* b;
public:
PlusExpr(Expr* e1, Expr* e2): a(e1), b(e2) { }
virtual int eval() { return a->eval() + b->eval(); }
};
int main() {
Literal* expr = new Literal(0);
for (int i = 0; i < 2000000000; i++)
expr->eval();
return 0;
}
type
TExpr = object ## abstract base class for an expression
TLiteral = object of TExpr
x: int
TPlusExpr = object of TExpr
a, b: ref TExpr
method eval(e: ref TExpr): int =
# override this base method
quit "to override!"
method eval(e: ref TLiteral): int = return e.x
method eval(e: ref TPlusExpr): int =
# watch out: relies on dynamic binding
return eval(e.a) + eval(e.b)
proc newLit(x: int): ref TLiteral =
new(result)
result.x = x
proc newPlus(a, b: ref TExpr): ref TPlusExpr =
new(result)
result.a = a
result.b = b
var expr = newLit(0)
for i in 1..2000000000:
discard eval(expr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment