// file: primes.java // author: Robert Keller // purpose: test lazy evaluation using primes // To test main use: java -cs primes import polya.*; import java.io.*; import java.util.*; // squares does not reuse the Growable, although it could in principal class primes { static public Polylist all = Polylist.cons(new Long(2), new Incremental(new oddprimes())); static public void main(String []arg) { int numberToPrint = 1000; System.out.println(all.prefix(numberToPrint)); } } // oddprimes is the Polylist of primes (3 5 7 11 ... ) class oddprimes extends Growable { long n; oddprimes() { n = 3; } public Object grow() { loop: for( ; ; n+=2 ) { for( Enumeration e = primes.all.elements(); ; ) { long trial = (((Long)(e.nextElement())).longValue()); if( n % trial == 0 ) { continue loop; } if( trial*trial > n ) break loop; } } Long first = new Long(n); n+=2; return Polylist.cons(first, new Incremental(this)); } }