You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Part 1: A Prime Sieve Formulated as a Lazy Stream

Due: 11:59pm Wednesday, Dec 16, 2020

Overview

Write a (functional) Java program that constructs primes, the lazy inifinite stream of prime numbers 2, 3, 5, 7, ... where numbers are represented using Java type int.  Ignore the fact that the int type only supports integer values less than 2^31.  We will only compute the first million or so primes (about 2^20), so no one will notice.  Obviously such a program could easily be generalized to use type long or the unbounded integer type java.math.BigInteger.  The support file primeSieve.java provides the interface IntStream which is the root of a composite class hierarchy supporting lazy streams of int, including  methods to print finite ones in conventional Lisp-like notation.  The formulation of streams supported in Java starting with Java 8 is not functional.  Simple operations like extracting the first element of a stream or the length of a finite stream destroy the stream.  Consequenlty, we must develop our own IntStream library from scratch.  Fortunately, it is not very difficult and requires comparatively little code.  The equivalent program in Haskell (generalized to unbounded integers) is simply

primes = filterPrime [2..]
  where filterPrime (p:xs) =
          p : filterPrime [x | x <- xs, x `mod` p /= 0]

Of course, Haskell has built-in support for lazy streams and the recursive definition of functions (like filterprime) using pattern matching all supported by an aggressive optimizing compiler.  Your task is to extend the provided code to support a static final field called primes in the top-level interface IntStream bound to the lazy infinite stream of primes (ignoring the fact that int arithmetic will overflow when numbers get too large.  You also need to write a JUnit test file (compatible with JUnit 4 as provided by DrJava) called IntStreamTest to test your code.  You may assume that all of the provided code is correct; you do not need to test the interface that it supports.

If I make any enhancements to the support code file primeSieve.java, I will post messages to that effect to Piazza.

Complications

Java is strictly a call-by-value language and lacks macros, so we are going to have to wrap the stream argument in a "cons" construction in a suspension (an object with a method to evaluate it and a cell to store that value).  This will make translating the simple Haskell code above more cumbersome.  There is a price to writing functional code in Java, a language not intended to support lazy evaluation.  In Racket/Scheme, we would make the stream cons operation a macro that automatically performs the wrapping.

  • No labels