File: sieve.ml

package info (click to toggle)
ocaml 4.02.3-9
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 22,076 kB
  • ctags: 30,429
  • sloc: ml: 154,213; ansic: 38,324; sh: 5,236; makefile: 4,569; asm: 4,283; lisp: 4,224; awk: 88; perl: 87; fortran: 21; cs: 9; sed: 9
file content (45 lines) | stat: -rw-r--r-- 1,557 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
(***********************************************************************)
(*                                                                     *)
(*                                OCaml                                *)
(*                                                                     *)
(*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         *)
(*                                                                     *)
(*  Copyright 1996 Institut National de Recherche en Informatique et   *)
(*  en Automatique.  All rights reserved.  This file is distributed    *)
(*  under the terms of the Q Public License version 1.0.               *)
(*                                                                     *)
(***********************************************************************)

open Printf
open Thread

let rec integers n ch =
  Event.sync (Event.send ch n);
  integers (n+1) ch

let rec sieve n chin chout =
  let m = Event.sync (Event.receive chin)
  in if m mod n = 0
     then sieve n chin chout
     else Event.sync (Event.send chout m);
          sieve n chin chout

let rec print_primes ch max =
  let n = Event.sync (Event.receive ch)
  in if n > max
     then ()
     else begin
            printf "%d\n" n; flush stdout;
            let ch_after_n = Event.new_channel ()
            in Thread.create (sieve n ch) ch_after_n;
               print_primes ch_after_n max
          end

let go max =
  let ch = Event.new_channel ()
  in Thread.create (integers 2) ch;
     print_primes ch max;;

let _ = go 50

;;