Hello.
> In fact, I was wondering
> if Lwt's authors would be against adding a function like:
>
> let wrap f x = try Lwt.return (f x) with e -> Lwt.fail e
Not a very good idea, since evaluation of wrap'ped
function's arguments can raise an exception that
won't be caught by wrap, suppose:
let lwt_string_of_int = wrap string_of_int
let () = Lwt_main.run (
lwt_string_of_int (raise Exit) >>= fun s ->
Lwt_io.printf "everything's okay buddies, it's %s\n" s
)
So it's up to the caller to guarantee the absence of
native exceptions. It's bad. If I will ever need to write
such wrapper, I will make it to have type
wrap : (unit -> ('a -> 'b)) -> (unit -> 'a) -> 'b Lwt.t
maybe with the name of function too, and with
early evaluation of first argument, like
let wrap ?(funcname="") u_f =
let r_f =
try
`Ok (u_f ())
with e_f ->
`Error e_f
in
match r_f with
| `Ok f -> fun x ->
try
Lwt.return (f x)
with e_x ->
(* 1.either *)
Lwt.fail (Failure (Printf.sprintf
"error evaluating function %S: %s"
funcname (Printexc.to_string e_x)))
(* 1.or *)
Lwt.fail e_x
| `Error e_f ->
(* 2.either *)
failwith (Printf.sprintf
"the wrapped function %S itself \
raises error: %s"
funcname (Printexc.to_string e_f))
(* 2.or *)
fun _u_x ->
Lwt.fail e_f
(I haven't checked this code! I don't remember
where should I set begin-end or parenthesis in
nested matches in the original syntax, and I don't
want to remember it now.)
I like the uniform error handling. So I have
wrapped the common IO-specific functions
to a library that gives IO_lwt for lwt, IO_direct
for direct OCaml I/O (stdlib), and... functor
functor functor it sometimes.
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.
But it doesn't matter, since I'm not a academician,
I'm an engineer.
So I'm using
IO.catch : (unit -> 'a m) -> (exn -> 'a m) -> 'a m
even for direct IO computations.
--
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