(* Il tipo degli stream *) type 'a streamCell = Nil | Cons of 'a * 'a stream and 'a stream = 'a streamCell lazy_t;; let rec fibs_aux first second = lazy (Cons(first,fibs_aux second (first + second)));; (* lo stream infinito dei numeri di Fibonacci *) let fibs = fibs_aux 1 1;; (* incrementale *) let rec union s1 s2 = match (Lazy.force s1) with Nil -> s2 | Cons(h,t) -> lazy (Cons(h,union s2 t));; let rec from n = lazy (Cons(n,from (n + 1))) (* incrementale: lascia solo gli elementi di s che soddisfano il predicato p *) let rec stream_filter s p = match (Lazy.force s) with Nil -> lazy Nil | Cons(x,s') -> if (p x) then lazy (Cons(x,stream_filter s' p)) else stream_filter s' p let not_divisible divisore dividendo = (dividendo mod divisore) > 0 (* incrementale perche' c'e' un numero infinito di numeri primi *) let rec sieve s = match (Lazy.force s) with Nil -> lazy Nil | Cons(head,s') -> lazy (Cons(head,sieve (stream_filter s' (not_divisible head)))) (* lo stream infinito dei numeri primi *) let primes = sieve (from 2) (* incrementale: da' lo stream dei primi n elementi di uno stream *) let rec take n s = match (n,Lazy.force s) with (0,_) -> lazy Nil | (_,Nil) -> lazy Nil | (_,Cons(x,s')) -> lazy (Cons(x,take (n - 1) s'));; (* monolitica *) let print s = let rec print_aux s' = match (Lazy.force s') with Nil -> print_string "" | Cons(x,s'') -> match (Lazy.force s'') with Nil -> print_int x | Cons(x',_) -> print_int x; print_string ";"; print_aux s'' in print_string "["; print_aux s; print_string "]"