packages feed

alms-0.4.9: examples/session-types-interactive.alms

(* An example with session types, including recursion.
   Reads natural numbers (very brittle) from standard input
   until getting a blank line, then prints the sum. *)

#load "libthread"
#load "libsessiontype"

open SessionType

type protocol = ?int; 1 |+| !int; protocol

let server =
  let rec loop (acc : int)
               (c   : protocol dual channel)
               : unit =
      match follow c with
      | Left c ->
          send c acc;
          ()
      | Right c ->
          let (x, c) = recv c in
            loop (acc + x) c
   in loop 0

let client =
  let rec loop (c : protocol channel) : int =
    let s = getLine () in
      if s == ""
                then
                    let c      = sel1 c in
          let (r, _) = recv c in
            r
        else
          let c      = sel2 c in
          let c      = send c (int_of_string s) in
            loop c
   in loop

let main =
  fun _ : unit ->
    let rv = newRendezvous[protocol] () in
      AThread.fork (fun _:unit -> server (accept rv));
      client (request rv)

in print (main ())