Search code examples
concurrencysmlsmlnjml

Generate natural numbers and printing them using 2 communication servers in Concurrent ML


I have a homework where i need to write 2 communication servers, one which generates natural numbers and the other which prints them. the generating server will be sending to the printing server. The servers should communicate over the shared channel chan.The main function should spawn a thread for each server.

`

    val sender = fn : int -> unit

    val receiver = fn : unit -> 'a

    val main = fn : unit -> unit

`

And so far this is code i have written:

`

     datatype 'a inflist = NIL

                | CONS of 'a * (unit -> 'a inflist);

     fun HD (CONS(a,b)) = a

              | HD NIL = raise Subscript;

    fun TL (CONS(a,b)) = b()

             | TL NIL = raise Subscript;

    fun NULL NIL = true
             | NULL _ = false;

    fun TAKE(xs, 0) = []

          | TAKE(NIL, n) = raise Subscript

          | TAKE(CONS(x,xf), n) = x::TAKE(xf(), n-1);


     fun FROMN n = CONS (n,fn () => FROMN (n+1));

     val natnumber = FROMN 0;

     fun printGenList f (h::t) = (f h;  printGenList f t);



     fun printList l = printGenList (fn(e) => print(Int.toString(e)^" ")) l;



      fun printPairList l = printGenList (fn(e,f) => print("("^Int.toString(e)^", "^Int.toString(f)^") ")) l;

      CM.make "$cml/cml.cm";
       open CML;

     val chan: int chan = channel();

     fun gen ch () = send (ch, printList(TAKE(natnumber,101)));

      fun printnat ch () = recv (ch);

    fun main () =

    let 

          val ch = channel() :int chan ;

         val _ = spawn (gen ch);

        val _ = spawn (printnat ch); 

  in

       ()

   end;

` But i am not getting the output. Am i going wrong in my syntax or the logic? I am new to SML and Concurrent ML. Please help me.


Solution

  • Why are you using a infinite list? There are simpler ways to implement this.