2 // Simple example to garbage collection.
9 // Define an algebraic datatype.
11 datatype EXP :: collectable = om
20 instantiate datatype EXP;
23 // Define a method that prints an expression. This is simple
24 // inductive definition
26 ostream& operator << (ostream& f, EXP e)
28 om: { return f << "om"; }
29 | num i: { return f << i; }
30 | var v: { return f << v; }
31 | add(a,b): { return f << '(' << a << " + " << b << ')'; }
32 | sub(a,b): { return f << '(' << a << " - " << b << ')'; }
33 | mul(a,b): { return f << '(' << a << " * " << b << ')'; }
34 | div(a,b): { return f << '(' << a << " / " << b << ')'; }
39 // Change all occurance of var(...) to t
41 void change (EXP& e, EXP t)
44 | num i: { e = add(e,add(e,e)); }
46 | add(a,b): { change(a,t); change(b,t); }
47 | sub(a,b): { change(a,t); change(b,t); }
48 | mul(a,b): { change(a,t); change(b,t); }
49 | div(a,b): { change(a,t); change(b,t); }
54 // Do a bunch of stuff that cons a lot
59 // (0 + x * 2) / (1 * 5 + 1 * 3) / (0 / y);
61 EXP t1 = div(div(add(num(0), mul(var('x'),num(2))),
62 add(mul(num(1), num(5)),mul(num(1),num(3)))),
63 div(num(0),var('y')));
65 EXP term = div(mul(t2,t2),t2);
68 cout << "[1] " << term << '\n';
71 cout << "[2] " << term << '\n';
73 term = t1; t1 = num(-1);
74 cout << "[3] " << term << '\n';
77 cout << "[4] " << term << '\n';
83 // start a collection.
84 GC::garbage_collect();