Lazy List in ML

Implementation of infinite sequence


datatype 'a seq = Nil
                 | Cons of 'a * (unit -> 'a seq) ;


exception Empty ;

fun hd (Cons (x,xf)) = x 
   | hd Nil          =  raise Empty;

fun tl (Cons(x,xf)) = xf()
     |  tl Nil      =  raise Empty ;


fun cons(x,xq) = Cons(x, fn() => xq) ;

fun from k = Cons(k, fn() =>from(k+1)) ;


exception Subscripts ;

fun take (xq, 0 )  =  [] 
  | take (Nil,n)   = raise Subscript
  | take (Cons(x,xf),n)  = x::take(xf(), n-1) ;

exception Null ;
fun Nth (Nil, _ ) = raise Null
   | Nth ( Cons(x,xf), 1) = x
   | Nth ( Cons(x,xf),n) = Nth(xf(),n-1) ;


fun interleave (Nil, yq) = yq
   |  interleave ( Cons(x,xf), yq ) =
        Cons(x, fn() =>  interleave (yq, xf())) ;

fun map f Nil = Nil 
  |  map f (Cons(x,xf)) = Cons(f  x , fn() => map f (xf())) ;

fun filter pred Nil          =     Nil
  | filter pred (Cons(x,xf)) =
           if  pred x then Cons(x, fn() => filter pred (xf()))
           else filter pred (xf()) ;


fun iterates f x  = Cons(x,  fn() => iterates f ( f x)) ;




fun toList Nil = []   (* represent the inf seq as a list *)
  | toList (Cons(x,xf)) = x :: toList (xf());

fun fromList L = List.foldr cons Nil L ; (* construct sequence from given list L *)

Compiler.Control.Print.printLength := 1000 ;



Applications :