/* Sieve of Eratosthenes This example is an implementation of the well known "Sieve of Eratosthenes". The object of the program is to sum all the primes from the first prime 2 to LIMIT. The algorithm is well known. Briely, a stream of candidate prime numbers is passed through a pipeline of filters. The first number in the stream is a new prime. Each filter looks for numbers which are not multiples of the prime the filter represents -- such numbers are potentially prime and are passed on to the next filter in the pipeline. */ type ORDERED context stream INT type ONE context single INT procedure filter (pipe, sum, sigma) let next := ordered let prime, candidate := _ -> INT : { pipe ? prime pipe ? candidate test (prime*prime) < LIMIT : { let new'sum = sum + prime : // filter (next, new'sum, sigma) . while candidate != NULL : test (candidate % prime)=0 : pipe ? candidate else {next ! candidate pipe ? candidate } . next ! NULL } else let result := sum + prime : { while candidate != NULL : { result := result + candidate pipe ? candidate } sigma ! result } . } procedure source(pipe) { {i for LIMIT/2-1 from 3 by 2 : pipe ! i } pipe ! NULL } let sum := _ -> INT let pipe := ordered : { //filter(pipe, 2, sigma) . //source(pipe) . sigma ? sum printf("Sum of primes: %d.\n", sum) }