lwt
lwt copied to clipboard
How do I make my IO recursively loop?
This is my code. It takes an input and interprets it. However, I'd like to make it recursively take an input, rather than just taking an input a limited number of times. What is the simplest way to do this? The issue here is that whatever method I use to loop it results in the interp function running after every expected input is resolved rather than running after each input is resolved. The interp
let server () =
let p =
let%lwt input = (Lwt_io.read_line Lwt_io.stdin) in
Lwt.return (interp input) in
p
let () = Lwt_main.run (server ());
This is the interp function:
let interp buf =
Lwt_io.printf "input: %s" buf;
I'm not entirely sure, but I guess you want something like
let server () =
let rec read_and_interp () =
match%lwt Lwt_io.read_line Lwt_io.stdin with
| line ->
interp input;
read_and_interp () (* start again after interp *)
| exception End_of_file ->
Lwt.return () (* don't start again at the end *)
in
read_and_interp ()
Or alternatively
let server () = Lwt_stream.iter interp Lwt_io.read_lines Lwt_io.stdin