Hello.

>> It uses "bind" and "return", but I'm very unsure
>> whether the code can be called "monadic IO",
>> since lwt itself does not respect the monad laws.
>
> What monadic laws lwt does not respect ?

  Lwt sees values of type Lwt.t not as IO actions,
but sometimes as the values of these actions.

  It does not respect the monad associativity:

    (m >>= f) >>= g   ==   m >>= (fun x -> f x >>= g)

  Look at the source, see the left and the right
parts of this law as the "res" values, uncomment
either block, run the program, enter two lines
of text to program's stdin and see the output.
The output should be the same in both cases
if the law is respected.

==============
open Lwt;

value () = Printf.printf "case 1, enter two lines:\n%!";
value m = Lwt_io.read_line Lwt_io.stdin;
value f_v = Lwt_io.read_line Lwt_io.stdin;
value f = fun _ -> f_v;
value g = Lwt.return;
value res = (m >>= f) >>= g;

(*
value () = Printf.printf "case 2, enter two lines:\n%!";
value f_v = Lwt_io.read_line Lwt_io.stdin;
value m = Lwt_io.read_line Lwt_io.stdin;
value f = fun _ -> f_v;
value g = Lwt.return;
value res = m >>= (fun x -> f x >>= g);
*)

value () = Lwt_main.run (res >>= fun s ->
  Lwt_io.write_line Lwt_io.stdout ("res = " ^ s));
==============

  In the first case it's:

case 1, enter two lines:
a
b
res = b

  In the second case it's:

case 2, enter two lines:
a
b
res = a

  When I began to use Lwt, I was badly surprised
by the fact that Lwt.t values are not real I/O actions.
So I had to get a new habit: if the top-level module
value has type Lwt.t 'a, I have to defer its
computation by wrapping it under "fun () -> <expr>".
And I have to remember which of my functions return
Lwt.t values, which of my abstract types really have
type Lwt.t 'a or contain the Lwt.t 'a values, to defer
their computations/sideeffects too.

-- 
Caml-list mailing list.  Subscription management and archives:
https://sympa-roc.inria.fr/wws/info/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs

Reply via email to