1

I'm creating a chat server, and I have a function that handles login. There exists a preset ref called nick and a preset input stream imp. My code is as follows:

let handle_login nr (inp,outp) = 
Lwt_io.printl "<Enter your 'nick'name>" >>= Lwt.return(nick := (Lwt_io.read_line inp))

However, this code give me the error:

Error: This expression has type string Lwt.t
       but an expression was expected of type string.

I know that the following code does work:

let handle_login nr (inp,outp) = 
Lwt_io.printl "<Enter your 'nick'name>" >>= Lwt.return(nick := "Jane")

In short, I don't know how to assign vars to values obtained from threads.

glennsl
  • 28,186
  • 12
  • 57
  • 75
Elsa
  • 43
  • 6

1 Answers1

1

I'm not very familiar with Lwt, but if it works like any other monad I would think this should work:

let handle_login nr (inp, outp) = 
  Lwt_io.printl "<Enter your 'nick'name>"
  >>= fun () -> Lwt_io.read_line inp
  >>= fun str -> Lwt.return (nick := str)

But I have to point out as well that mutating shared state from async code is a disaster waiting to happen. That you can do it certainly doesn't mean you should.

Elsa
  • 43
  • 6
glennsl
  • 28,186
  • 12
  • 57
  • 75
  • It's generally safe to mutate shared state from Lwt code (and Async code, and JS promise code), because all the callbacks run on the main thread, and cannot be preempted. As long as you are sure all possible interleavings at the granularity of entire callbacks are safe, or take steps to ensure that, there won't be a problem. This is by design: these libraries are, in part, *meant* to make it easy to mutate shared state, so you *should* :) – antron Apr 15 '19 at 14:41
  • 1
    @antron Ah, sorry. I guess I'm being a bit too bombastic. I meant it in a broader sense as well though, in that it requires a fair bit of discipline, and ideally a proper plan, to avoid surprises when going beyond the most trivial scenarios. – glennsl Apr 15 '19 at 15:44
  • I’ll be using mutexes so I should be able to avoid those issues. – Elsa Apr 15 '19 at 19:10