Merge remote branch 'master'
[prop.git] / tests / hashcons2.pcc
blob25d0ac4ea23013ce75d7a90122a7d73ab069dc36
1 //
2 //  This is a simple (and useless) example for testing the hash cons feature
3 //  in Prop.
4 //
5 #include <iostream.h>
6 #include <new>
8 int balance = 0;
10 datatype EXP :: unique traced = num (int)
11                               | add (EXP, EXP)
12                               | sub (EXP, EXP)
13                               | mul (EXP, EXP)
14                               | div (EXP, EXP)
15 public: {  inline void * operator new    (size_t n) { balance++; cerr << '+'; return new char [n]; }
16            inline void   operator delete (void * x) { balance--; cerr << '-'; delete [] ((char*)x); }
17         }
19 and LIST :: unique traced     = nil
20                               | list (EXP, LIST)
21 public: {  inline void * operator new    (size_t n) { balance++; cerr << '>'; return new char [n]; }
22            inline void   operator delete (void * x) { balance--; cerr << '<'; delete [] ((char*)x); }
23         }
27 //  implement the datatypes.
29 instantiate datatype EXP, LIST; 
31 ostream& operator << (ostream& f, EXP e)
33    match (e) {
34       num n:    { return f << n; }
35    |  add(x,y): { return f << '(' << x << " + " << y << ')'; }
36    |  sub(x,y): { return f << '(' << x << " - " << y << ')'; }
37    |  mul(x,y): { return f << '(' << x << " * " << y << ')'; }
38    |  div(x,y): { return f << '(' << x << " / " << y << ')'; }
39    }
42 ostream& operator << (ostream& f, LIST l)
44    match (l) {
45       case nil:           return f;
46       case list(e,nil):   return f << e;
47       case list(e,t):     return f << e << ',' << t;
48    }
51 void do_something()
53    cout << "Balance = " << balance << '\n'
54         << "EXP  hash table size = " << EXP_universe.size() << '\n'
55         << "LIST hash table size = " << LIST_universe.size() << '\n';
56    EXP e1 = mul(add(num(1),num(2)), add(num(2), num(3)));
57    EXP e2 = mul(add(num(1),num(2)), add(num(2), num(3)));
58    LIST l1 = list(e1, list(e2, nil));
59    cout << l1 << '\n';
60    cout << ((e1 == e2) ? "Good!\n" : "Bad boy! Naughty, naughty boy!\n");
61    cout << ((num(1) == num(1)) ? "Good!\n" : "Bad boy! Naughty, naughty boy!\n");
62    cout << ((num(1) != num(2)) ? "Good!\n" : "Bad boy! Naughty, naughty boy!\n");
63    cout << ((add(e1,e2) == add(e1,e2)) ? "Good!\n" : "Bad boy! Naughty, naughty boy!\n");
64    cout << ((add(e1,e2) != add(e1,num(2))) ? "Good!\n" : "Bad boy! Naughty, naughty boy!\n");
65    cout << "Balance = " << balance << '\n'
66         << "EXP  hash table size = " << EXP_universe.size() << '\n'
67         << "LIST hash table size = " << LIST_universe.size() << '\n';
70 int main() 
72    do_something();
73    cout << "Balance = " << balance << '\n'
74         << "EXP  hash table size = " << EXP_universe.size() << '\n'
75         << "LIST hash table size = " << LIST_universe.size() << '\n';
76    return 0;