/* Prime sieve */ /* using (finite) streams */ #use choice stream { Next; < > Empty; }; typedef stream; stream \$c count(int n) { for (int i = 2; i < n; i++) //invariant \$c : stream { \$c.Next; /* \$c : */ send(\$c, i); /* \$c : stream */ } \$c.Empty; /* \$c : < > */ close(\$c); } stream \$t filter(int p, stream \$s) { switch (\$s) { case Empty: { wait(\$s); \$t.Empty; close(\$t); } case Next: { int x = recv(\$s); if (x % p != 0) { \$t.Next; send(\$t, x); } \$t = filter(p, \$s); /* tail-call */ } } } stream \$p primes(stream \$s) { switch (\$s) { case Empty: { wait(\$s); \$p.Empty; close(\$p); } case Next: { int x = recv(\$s); \$p.Next; send(\$p, x); stream \$t = filter(x, \$s); \$p = primes(\$t); } } } void print_stream(stream \$s) { while (true) { switch (\$s) { case Empty: { /* \$s : < > */ wait(\$s); print("\n"); return; } case Next: { /* \$s : */ int x = recv(\$s); /* \$s : stream */ printint(x); print(" "); break; } } } } int main() { stream \$nats = count(100); stream \$primes = primes(\$nats); print_stream(\$primes); return 0; }