(* Whether there are any odd factors m of n such that m>=k. Requires: k>=3, n>=1 *) fun noOddFactors(k,n) = k*k > n orelse n mod k <> 0 andalso noOddFactors(k+2,n) (* Whether n is prime. Requires: n>=2 *) fun isPrime(n) : bool = n = 2 orelse n mod 2 = 1 andalso noOddFactors(3,n) fun nextPrime(n) : int = if isPrime(n+1) then n+1 else nextPrime(n+1) (* Returns: the next number larger than p and indivisible by any number in l *) fun sieve(p:int, l: int list) = if List.all (fn (n) => p mod n <> 0) l then p else sieve(p+1, l) fun sieve_state(p:int, l:int list): int*int list = let val p' = sieve(p,l) in (p', p'::l) end val s = Stream2.make((2,[2]), fn(p,l) => (p,sieve_state(p,l)));