Using Async Reader to read user input


I want to write a function that simple echos a user’s input in stdin, until user enter “exit”.
My approach is to define a recursive function and use Async’s Reader module to read user input and recursively call the function.

let rec read_and_print () : unit Deferred.t =
  let stdin = Lazy.force Reader.stdin in
  print_endline "Enter Message: ";
  Reader.read_line stdin
  >>| function
  | `Eof -> print_endline "error"
  | `Ok "exit" -> ()
  | `Ok x -> 
    print_endline x;
    read_and_print ()

However, i get this error:

How do I solve this?

The issue is that in your first two cases, you are “returning” a unit, while in the third case, you are returning a unit Deferred.t.

One way to fix this is by forcing the first two cases to return a unit Deferred.t as well. i.e.

print_endline “error”;

Also, you would need to change your map operator (>>|) to bind operator (>>=), in order to typecheck.

It works after I changed the code following your suggestions. Thank you so much!