Problem with running lwt code


open Lwt

let rec repeat_function_with_delay () =
  let my_function () =
    Lwt_io.printl "Function called" in
  my_function () >>= fun () ->
  Lwt_unix.sleep 1.0 >>= fun () ->  (* Delay of 1 second *)
  repeat_function_with_delay ()

let () =
  Lwt_main.run (repeat_function_with_delay ())

I got error: Error: Unbound module Lwt_io

I’ve put lwt in my dune’s libraries.

Did you use the correct library name in the dune file? See the example on this page: https://dune.build/

You need to also add lwt.unix in the libraries field of your dune file.

(The separation between lwt and lwt.unix is because Lwt aims to be friendly to js_of_ocaml in which the linux part of the library is not used.)


I’d also recommend that you open Lwt.Syntax which then gives you let* binding operators.

open Lwt

let rec repeat_function_with_delay () =
  let my_function () =
    Lwt_io.printl "Function called" in
  let* () = my_function () in
  let* () = Lwt_unix.sleep 1.0 in  (* Delay of 1 second *)
  repeat_function_with_delay ()

It doesn’t make much difference on a small example like this with just () values. But it’s nicer on bigger programs. Might as well start using this early.

2 Likes

Thanks for the solution! The following information is critical for new comers, but it doesn’t mention in documentation.

‘lwt.unix’ information

1 Like