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 46 47 48 49 50 51 52
|
(**
* sieve.sml
*
* @copyright (C) 2021 SML# Development Team.
* @author UENO Katsuhiro
*)
structure Sieve : sig
val sieve : int -> unit
end =
struct
fun stream max =
let
val out = MVar.new ()
fun loop i =
if i <= max
then (MVar.put (out, SOME i); loop (i+1))
else (MVar.put (out, NONE); Pointer.NULL () : unit ptr)
in
Pthread.create (fn _ => loop 2);
out
end
fun filter f input =
let
val out = MVar.new ()
fun loop () =
case MVar.take input of
NONE => (MVar.put (out, NONE); Pointer.NULL () : unit ptr)
| SOME x => (if f x then MVar.put (out, SOME x) else (); loop ())
in
Pthread.create (fn _ => loop ());
out
end
fun sieve max =
let
val input = stream max
fun loop input =
case MVar.take input of
NONE => ()
| SOME x =>
(print (Int.toString x ^ "\n");
loop (filter (fn y => y mod x <> 0) input))
in
loop input
end
end
|