ocamllwt

Lwt 2.7.0 type error


I wrote this piece of code with Lwt 2.7.0 :

open Lwt

let listen_address = Unix.inet_addr_loopback
let port = 9000
let backlog = 1

let () = Lwt_log.add_rule "*" Lwt_log.Info

let create_socket () =
  let open Lwt_unix in
  let sock = socket PF_INET SOCK_STREAM 0 in
  let sockaddr = ADDR_INET(listen_address, port) in
  let%lwt () = Lwt_unix.Versioned.bind_2 sock sockaddr in
  listen sock backlog;
  sock

And I got this error (on the last line, i.e. sock) :

Error: This expression has type Lwt_unix.file_descr
       but an expression was expected of type 'a Lwt.t

Well, yes, sock is of type Lwt_unix.file_descr, why would the compiler throw this program and force the type 'a Lwt.t ? (when I ask what type was found for create_socket it tells me it's of type unit -> '_a)

P.S. : Thanks to Daniil Baturin : http://baturin.org/code/lwt-counter-server/


Solution

  • The compiler has not forced the type of the result to unit, it forced the type of the argument to unit because the argument pattern you have is ().

    let%lwt is Lwt.bind, so the continuation (after the in) must evaluate to a promise (_ Lwt.t). Since sock is Lwt_unix.file_descr and not a promise, you must wrap it: Lwt.return sock.

    More context might be needed to answer your question about the warning, I'm leaving you a comment.