ocamlocaml-lwt

What's the proper usage for Lwt_io.read_int?


How do you properly use Lwt_io.read_int? I tried what I thought was the obvious usage but I don't get obvious results...

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
    )

I compiled, ran and inputed 12345 when prompted and the program displayed 875770417.

I'm missing something here...

With the help below I arrived at this. It works and I hope its correct.

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"
        )
    )

I think I should post some code to demonstrate the proper usage of 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
    )

Solution

  • This reads a binary encoded integer, for example in order to deserialize some data from a file.

    You read 875770417 which is in hex 0x34333231, which in turns corresponds to the ASCII encoding of '1', '2', '3', and '4' in little endian ordering.

    You probably want to read a string using Lwt_io.read_line and convert the result using int_of_string.