(* Prime number stream *) ltype Stream a = &{stop: 1; next: a /\ Stream a};; from : Int -> {Stream Int};; 'c <- from n = case 'c of | next -> send 'c n ; 'c <- from (n+1) | stop -> close 'c ;; filter: (a -> Bool) -> {Stream a <- Stream a};; 'c <- filter q -< 'd = case 'c of | stop -> 'd.stop ; wait 'd ; close 'c | next -> 'c <- filterNext q -< 'd and filterNext : (a -> Bool) -> {a /\ Stream a <- Stream a};; 'c <- filterNext q -< 'd = 'd.next ; (* 'd : a /\ Stream a *) n <- recv 'd ; (* 'd : Stream a *) (case q n of | True -> send 'c n ; 'c <- filter q -< 'd | False -> 'c <- filterNext q -< 'd) ;; not : Bool -> Bool;; not b = if b then False else True;; divides : Int -> Int -> Bool;; divides d n = ((n / d) * d = n);; sieve : {Stream Int <- Stream Int};; 'c <- sieve -< 'd = case 'c of | stop -> 'd.stop ; wait 'd ; close 'c | next -> 'd.next ; p <- recv 'd ; send 'c p ; 'e <- filter (fun n -> not (divides p n)) -< 'd ; 'c <- sieve -< 'e ;; primes : {Stream Int};; 'c <- primes = 'd <- from 2 ; 'c <- sieve -< 'd ;; (* sample client *) print_stream : Int -> {1 <- Stream Int};; 'c <- print_stream n -< 'd = if n > 0 then 'd.next; x <- recv 'd; print x; print_str " "; 'c <- print_stream (n-1) -< 'd else 'd.stop; wait 'd; print_str "\n"; close 'c ;; 'top <- 'c <- primes; 'u <- print_stream 25 -< 'c; wait 'u; close 'top ;;