(* Examples using language-integrated lazy evaluation in SML/NJ.
Note that these examples use an extension of SML implemented only
in SML/NJ.
See Harper, Programming in Standard ML, Chapter 15 for reference.
http://www.cs.cmu.edu/~rwh/smlbook/book.pdf *)
(* Enable SML/NJ-specific lazy extensions to SML. *)
Control.lazysml := true;
open Lazy;
(* Values of type 'a stream are *computations* that produce values of
the form Cons (v,s) *)
datatype lazy 'a stream = Cons of 'a * 'a stream
(* The streams of ones. *)
val rec lazy ones = Cons (1, ones)
(* Natural numbers *)
val rec lazy nats =
let fun lazy f x = Cons (x, f (x+1))
in f 0 end
(* Powers of 2 *)
val rec lazy powers2 =
let fun lazy f x = Cons (x, f (x*2))
in f 2 end
(* Build a stream using a given step function and seed value x *)
fun lazy make_stream step x = Cons (x, make_stream step (step x))
(* Get one value from the stream. *)
val Cons (zero,rest) = nats
(* Get another value from rest of the stream. *)
val Cons (another,more) = rest
(* Get three values from a stream. *)
val Cons (first, Cons (second, Cons (third, s))) = powers2
(* smap Map a stream to another stream where each element in the result
stream is f applied to the corresponding element in the original
stream. *)