COS 441 - Lazy evaluation lecture notes


This is a lazy program, it won't work in (strict) SML/NJ.
fun integersFrom i = i :: integersFrom(i+1)

fun removeMultiples(a,b::rest) = 
  if b mod a = 0 then removeMultiples(a,rest) 
                 else b::removeMultiples(a,rest)

fun sieve (a::rest) = a :: sieve(removeMultiples(a,rest))

val primes = sieve (integersFrom 2) 

fun nth(a::rest, 0) = a | nth(a::rest,i) = nth(rest,i-1)

val x = nth(primes,1) + nth(primes,2)
Here's a strict version. But it's inefficient and insufficiently general:
fun integersFrom i = if i<100 then i :: integersFrom(i+1) else nil

fun removeMultiples(a,b::rest) = 
  if b mod a = 0 then removeMultiples(a,rest) 
                 else b::removeMultiples(a,rest)
  | removeMultiples(a,nil) = nil

fun sieve (a::rest) = a :: sieve(removeMultiples(a,rest))
  | sieve nil = nil

val primes = sieve (integersFrom 2) 

fun nth(a::rest, 0) = a | nth(a::rest,i) = nth(rest,i-1)

val x = nth(primes,1) + nth(primes,2)

Back to COS 441 front page | Course Newsgroup | Assignments