如何正确使用 Lwt_io.read_int?我尝试了我认为明显的用法,但没有得到明显的结果......
open Lwt.Infix
let _ =
Lwt_main.run
(
Lwt_io.print "Enter number: " >>=
fun () -> Lwt_io.read_int (Lwt_io.stdin) >>=
fun d -> Lwt_io.printf "%d\n" d
)
我编译运行并在提示时输入12345,程序显示875770417。
我在这里遗漏了一些东西......
在下面的帮助下,我做到了这一点。它有效,我希望它是正确的。
open Lwt.Infix
let _ =
Lwt_main.run
(
Lwt_io.print "Enter number: " >>=
fun () -> Lwt_io.read_line (Lwt_io.stdin) >>=
fun s ->
(
try
Lwt.return_some( Pervasives.int_of_string s)
with
| _ -> Lwt.return_none
) >>=
fun o ->
Lwt_io.print
(
match o with
| Some i -> Printf.sprintf "%d\n" i
| None -> "Ooops, invalid format!\n"
)
)
我想我应该发布一些代码来演示 Lwt_io.read_int 的正确用法。
open Lwt.Infix
open Lwt_io
let _ =
Lwt_main.run
(
let i, o = Lwt_io.pipe() in
Lwt_io.write_int o 1 >>=
fun () -> Lwt_io.flush o >>=
fun () -> Lwt_io.close o >>=
fun () -> Lwt_io.read_int i >>=
fun d -> Lwt_io.printf "%d\n" d >>=
fun () -> Lwt_io.close i
)