Standard ML 无穷数据

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

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

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

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

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

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


(*

   take( from( 30 ), 2 )
=> take( Cons( 30, fn() => from( 30 + 1 ) ), 2 )
=> 30 :: take( from( 30 + 1 ), 1 )
=> 30 :: take( Cons( 31, fn() => from( 31 + 1 ) ), 1 )
=> 30 :: 31 :: take( from( 31 + 1 ), 0 )
=> 30 :: 31 :: take( Cons( 32, fn() => from( 32 + 1 ) ), 0 )
=> 30 :: 31 :: []
=> [30, 31]
*)

fun squares( Nil ) : int seq = Nil
  | squares( Cons( x, xf ) ) = Cons( x * x, fn() => squares( xf() ) );
take( squares( from( 1 ) ), 10 );

fun add( Cons( x, xf ), Cons( y, yf) ) = Cons( x + y, fn() => add( xf(), yf() ) )
  | add _ : int seq = Nil;
take( add( from( 1000 ), squares( from( 1 ) ) ), 10 );

fun interleave( Nil, yq ) = yq
  | interleave( Cons( x, xf ), yq ) = Cons( x, fn() => interleave( yq, xf() ) );
take( interleave( from( 10 ), from( 50 ) ), 10 );

fun filter( pred, Nil ) = Nil
  | filter( pred, Cons( x, xf ) ) = 
        if pred( x ) then
   Cons( x, fn() => filter( pred, xf() ) )
else
   filter( pred, xf() );
take( filter( ( fn n => n mod 10 = 7 ), ( from 50 ) ), 10 );

fun fromList( l ) = List.foldr cons Nil l;

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

take( fromList( [1,2] ) @ from( 10 ), 10 );

你可能感兴趣的:([Data,Structure])